使用另一个结构指令

时间:2017-12-22 16:37:30

标签: angular angular2-directives angular-directive

我的AppComponent模板(在AppModule中引导)是

<div *myDir="let item of mySource">
  My Directive #{{item}}
</div>

其中mySource是具有list属性

的对象
mySource = { list: [1, 2, 3, 4, 5] };

因此,将myDir替换为ngFor*ngFor="let item of mySource.list")会给我

  

我的指令#1
  我的指令#2
  我的指令#3
  我的指令#4
  我的指令#5

我尝试与myDir配对实施myComponent,以便在ngFor Angular核心指令上提供模板化包装,以便能够通过mySource(而不是mySource.list import { MyComponent } from './my.component'; @Directive({ selector: '[myDir][myDirOf]' }) export class MyDirective { private source; constructor(/* ... */) { } @Input() set myDirOf(source) { this.source = source; } ngOnInit() { // dynamic wrapping with MyComponent const templateView = this.templateRef.createEmbeddedView({}); const compFactory = this.resolver.resolveComponentFactory(MyComponent); const componentRef = this.viewContainer.createComponent(compFactory, null, this.viewContainer.injector, [templateView.rootNodes]); // passing MyDir params to Mycomponent's instance componentRef.instance.source = this.source; componentRef.instance.template = this.templateRef; } } )并得出相同的结果。当然,最终目标要复杂得多,但我需要用最小的例子来解决这个问题......做了什么?

my.directive.ts

@Component({
  selector: 'app-my',
  template: `
<div *ngFor="let item of source.list">
  <ng-template
    [ngTemplateOutlet]="template"
    [ngTemplateOutletContext]="{
      item: item
    }">
  </ng-template>
</div>`
})
export class MyComponent implements OnInit {
  source;
  template;
  constructor() { }
}

my.component.ts

item

问题在于我无法将{{item}}传递回主机组件的模板,因此目前我只获得了包含&#34;我的指令#的5条相同的行# &#34;而ng-template并不起作用。 MyComponent的template看起来有点不对劲。它接受item但未通过Toast.makeText(AddAlbumActivity.this, getString(R.string.all_fields_mandatory), Toast.LENGTH_SHORT).show();

我根据目前的情况创建了一个可编辑的DEMO。另外,这是我需要的简单图表:

enter image description here

1 个答案:

答案 0 :(得分:1)

使用$implicit将数据传递到item

<强> my.component.html

<div *ngFor="let item of source.list">
  <ng-template
    [ngTemplateOutlet]="template"
    [ngTemplateOutletContext]="{
      $implicit: item
    }">
  </ng-template>

</div>

您的模板

<div *myDir="let item of mySource">
  My Directive #{{item}}
</div>

相当于

<ng-template myDir let-item [myDirOf]="mySource">
  <div>
    My Directive #{{item}}
  </div>
</ng-template>

但是如果模板变量(let-item)没有值,则默认情况下需要$implicit

<ng-template myDir let-item="$implicit" [myDirOf]="mySource">
  <div>
    My Directive #{{item}}
  </div>
</ng-template>

<强> DEMO

另见

相关问题