Skip to content

@ViewChildren('name') 使用name来选择多个元素 #261

@niaomingjian

Description

@niaomingjian

ViewChildren API例子 使用directive type来选择多个directive。
现在我想用name来选择多个元素如何写?
template中只能定义一个#abc。

Metadata Properties:

selector - the directive type or the name used for querying.
read - read a different token from the queried elements.

@Component({
  selector: 'app-root',
  template: `
    <pane id="1"></pane>
    <pane id="2"></pane>
    <pane #abc id="3" *ngIf="shouldShow"></pane>
    
    <button (click)="show()">Show 3</button>
    <button (click)="hide()">Hide 3</button>
       
    <div>panes: {{serializedPanes}}</div> 
  `,
})
export class ViewChildrenComp implements AfterViewInit {
  @ViewChildren('abc') panes: QueryList<ElementRef>;
  serializedPanes: string = '';
 
  shouldShow = false;
 
  show() { this.shouldShow = true; }
  hide() { this.shouldShow = false; }
 
  ngAfterViewInit() {
    this.calculateSerializedPanes();
    this.panes.changes.subscribe(
      (r) => {
      this.calculateSerializedPanes(); 
    });
  }
 
  calculateSerializedPanes() {
    setTimeout(
      () => {
        this.serializedPanes = this.panes.map(p => p.nativeElement.id).join(', '); 
      }, 0);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions