代码之家  ›  专栏  ›  技术社区  ›  r3plica

使用标识符的angular6@viewchildren

  •  0
  • r3plica  · 技术社区  · 6 年前

    我创建了一个带有选定 PYB按钮组 使用 @ViewChildren ,声明如下:

    @ViewChildren('header', { read: ElementRef }) headers: QueryList<ElementRef>
    

    我的HTML模板看起来有点像这样:

    <div class="container" *ngIf="categories">
      <div class="row" pyb-button-group>
        <div class="col-md-4 col-6" *ngFor="let category of categories">
          <a class="btn-choice" [routerLink]="['/' + category.id]">
            <div class="header" #header>
              <span class="title">{{ category.name }}</span>
            </div>
          </a>
        </div>
      </div>
    </div>
    

    所以我有一个方法 ngAfterViewInit 这样地:

    ngAfterViewInit() {
      console.log(this.headers);
    }
    

    它又回来了 undefined

    我做错什么了吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Lia    6 年前

    应该是这样的:

    @ContentChildren('header', { read: ElementRef }) headers: QueryList<ElementRef>
    
    ngAfterViewInit(){
     this.headers.toArray().forEach(el => {
          console.log(el);
      });
     }
    }
    

    DEMO

        2
  •  0
  •   Sreekumar P    6 年前

    它也适用于ViewChildren,

    export class AppComponent {
    
      @ViewChildren('header', { read: ElementRef }) headers: QueryList<ElementRef>
      categories: {
        name: string
      }[] = [];
    
      ngOnInit() {
        this.categories = [];
        this.categories.push({ name: "Test" }, { name: "Test2" });
      }
    
      ngAfterViewInit() {
        console.log(this.headers);
        this.headers.toArray().forEach(header => console.log(header));
      }
    }
    

    这是一个工作样品, https://stackblitz.com/edit/angular-jdkdro