Angular 2 dynamic instance link @ContentChild

I am using Angular 2.0.1.

I have a component that can accept any other component through <ng-content>- this works fine.

The problem I am facing is when I want to reference a nested component.

If I knew that there <ng-content>would be only one component, I could say: @ContentChild(MyComponent) dynamicTarget: IMyComponent;but since it can be any component (the only assumption I would make is that any injected component implements a certain interface), it becomes more complicated.

I also tried <ng-content #dynamicTarget'>and then referenced it, saying @ContentChild('dynamicTarget') dynamicTarget: IMyComponent;, but this returns undefined.

Does anyone know how I can tell Angular 2 that this thing is an instance of a component, so that I can try to call a function on it?

To clarify the use case, I have a multi-step wizard that can accept any component as content, and I want to call a function validatein the content (which, again, I would assume that an instance exists)

+4
source share
3 answers

One approach might be to provide the same #idfor any dynamic component. I have given #thoseThings. (I think it is almost the same as @Missingmanual)

PLUNKER (see console for matches.)

@Component({
  selector: 'my-app',
  template: `
  <div [style.border]="'4px solid red'">
    I'm (g)Root.

    <child-cmp>
      <another-cmp #thoseThings></another-cmp>
    </child-cmp>
  </div>
  `,
})
export class App {
}


@Component({
  selector: 'child-cmp',
  template: `
    <div [style.border]="'4px solid black'">
        I'm Child.
      <ng-content></ng-content>
    </div>
  `,
})
export class ChildCmp {
  @ContentChildren('thoseThings') thoseThings;

  ngAfterContentInit() {
    console.log(this.thoseThings);

    this.validateAll();

    if(this.thoseThings){
     this.thoseThings.changes.subscribe(() => {
       console.log('new', this.thoseThings);
     }) 
    }
  }

  validateAll() {
    this.thoseThings.forEach((dynCmp: any) => {
      if(dynCmp.validate)
       dynCmp.validate();  // if your component has a validate function it will be called
    });
  }
}


@Component({
  selector: 'another-cmp',
  template: `
    <div [style.border]="'4px solid green'">
        I'm a Stranger, catch me if you can.
    </div>
  `,
})
export class AnOtherCmp {
}
+3
source
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, Parent, Transcluded1, Transcluded2 ],
  providers: [
    {provide: TranscludedBase, useExisting: Transcluded1, multi:true}
    {provide: TranscludedBase, useExisting: Transcluded2, multi:true}
  ],
  bootstrap: [ App ]
})

+1

, validate , . IValidate,

@ContentChild('IValidate') dynamicTarget: IValidate;
// ...
this.dynamicTarget.validate();

Angular does not care about the exact class if it matches the requested interface.

-1
source

Source: https://habr.com/ru/post/1659770/


All Articles