kittencup / angular2-ama-cn

angular2 随便问
692 stars 101 forks source link

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

Open niaomingjian opened 7 years ago

niaomingjian commented 7 years ago

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);
  }
}
niaomingjian commented 7 years ago

在span中加上*ngIf="shouldShow",似乎就可以了,不会出现说#abc定义多次的编译error

@Component({
  selector: 'app-root',
  template: `
    <span #abc id="1"></span>
    <span #abc id="2" *ngIf="shouldShow"></span>
    <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; // or true

  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);
  }
}