按顺序获取不同指令的数组

时间:2017-03-05 07:58:33

标签: angular

我想从视图(或内容)中获取一些指令,其顺序与模板中指定的顺序相同。

尝试1 [plunker]

@Directive({selector: 'dir-1'}) class Dir1 {}
@Directive({selector: 'dir-2'}) class Dir2 {}
@Directive({selector: 'dir-3'}) class Dir3 {}

@Component({
  selector: 'my-app',
  template: `
<dir-1></dir-1>
<dir-2></dir-2>
<dir-3></dir-3>
  `,
})
export class App {
  @ViewChildren(Dir1) dir1s;
  @ViewChildren(Dir2) dir2s;
  @ViewChildren(Dir3) dir3s;
  ngAfterViewInit() {
    console.log(this.dir1s, this.dir2s, this.dir3s);
  }
}

只需使用不同的指令,就会失去订单

尝试2 [plunker]

@Directive({selector: 'general'}) class General {}
@Directive({selector: '[specific-1]'}) class Specific1 {}
@Directive({selector: '[specific-2]'}) class Specific2 {}
@Directive({selector: '[specific-3]'}) class Specific3 {}

@Component({
  selector: 'my-app',
  template: `
<general specific-1></general>
<general specific-2></general>
<general specific-3></general>
  `,
})
export class App {
  @ViewChildren(General) generals;
  ngAfterViewInit() {
    console.log(this.generals);
  }
}

通过&#34;将军&#34;选择器,我不再知道指令的类型

1 个答案:

答案 0 :(得分:2)

正如文件所说https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#find-a-parent-component-by-injection

  

在Angular中获取组件引用有点棘手。

所以你可以尝试以下技巧:

export abstract class BaseSpecific { }

const provideSpecific = (component: BaseSpecific) => {
  return { provide: BaseSpecific, useExisting: forwardRef(() => component) };
};

@Directive({ selector: '[specific-1]', providers: [provideSpecific(Specific1)] }) export class Specific1 implements BaseSpecific { }
@Directive({ selector: '[specific-2]', providers: [provideSpecific(Specific2)] }) export class Specific2 implements BaseSpecific { }
@Directive({ selector: '[specific-3]', providers: [provideSpecific(Specific3)] }) export class Specific3 implements BaseSpecific { }

@Directive({ selector: 'general' })
export class General {
  constructor(@Self() public specificClass: BaseSpecific) { }
}


@Component({
  selector: 'my-app',
  template: `
    <general specific-1></general>
    <general specific-2></general>
    <general specific-3></general>
  `
})
export class AppComponent {
  @ViewChildren(General) generals: QueryList<General>;

  ngAfterViewInit() {
    console.log(this.generals.map(x => x.specificClass.constructor.name));
  }
}

<强> Plunker Example