首页 > 解决方案 > 如何将每个 @ContentChildren 放入使用 *ngFor 生成的单个 div

问题描述

我试图在这里制作一些类似标签的组件,但我有一些问题。

这是我的组件的用法:

<app-ui-tab001-frame>
    <app-ui-tab001-item [tabTitle]="'titleA'">contentA</app-ui-tab001-item>
    <app-ui-tab001-item [tabTitle]="'titleB'">contentB</app-ui-tab001-item>
</app-ui-tab001-frame>

“app-ui-tab001-frame”的 html 就像:

<ul>
  <li *ngFor="let tab of tabArray.toArray()">

         <ng-content></ng-content>

  </li>
</ui>
<ul>
  <li *ngFor="let tab of tabArray.toArray()">
     <div>
         **I want to put each @ContentChildren here**
         **tried {{tab.elemRef.nativeElement.innerHTML}} here but not working**
     </div>
  </li>
</ui>

“app-ui-tab001-item”的 html 就像:

<div class="tab-pane" *ngIf="isActive">
  <ng-content></ng-content>
</div>

“app-ui-tab001-frame”的ts就像:

export class UiTab001FrameComponent implements OnInit,AfterContentInit {
  @ContentChildren(UiTab001ItemComponent) tabArray : QueryList<UiTab001ItemComponent>;

  constructor() { }


  ngOnInit() {

  }
  _checkWindowWidth(){

  }

  ngAfterContentInit(){

    console.log(this.tabArray.toArray());

  }

}

“app-ui-tab001-item”的ts就像:

export class UiTab001ItemComponent implements OnInit {
  @Input() isActive :boolean = false;
  @Input() tabTitle :string = null;
  public elemRef :ElementRef<any>;
  constructor(private elem :ElementRef<any>) { 
    this.elemRef = this.elem;
  }

  ngOnInit() {
  }

}

我想要的是将每个“app-ui-tab001-item”组件放入由 *ngFor 生成的单个 div(可能吗?),但我不知道如何使其工作。

我尝试在“app-ui-tab001-item”组件的 constructor() 函数中使用 elementRef,并将“{{tab.elemRef.nativeElement.innerHTML}} 注入这些 div,但它并没有起到作用我想要。实际上我是 Angular 的新手 :( 只需要有人指出我的错误

标签: angular

解决方案


是的你可以。ng-content只需将项目包装在其中ng-template并用于ngTemplateOutlet在列表组件中呈现项目。


@Component({
  selector: 'my-item',
  template: `
  <ng-template #content>
    <ng-content></ng-content>
  </ng-template>
  `
})
export class ItemComponent {
    @ViewChild('content', { static: true }) content: TemplateRef<void>;
}

@Component({
  selector: 'my-list',
  template: `
  <ul>
    <li *ngFor="let tab of tabArray">
      <div>
         <ng-template [ngTemplateOutlet]="tab.content"></ng-template>
      </div>
    </li>
  </ul>

  `
})
export class ListComponent {
    @ContentChildren(ItemComponent) tabArray : QueryList<ItemComponent>;
}

https://stackblitz.com/edit/angular-nukgpp?file=src%2Fapp%2Fapp.component.ts


推荐阅读