Reputation: 5635
A very basic setup, component:
export class LayerComponent {
public content: string;
constructor(content: string) {
this.content = content;
}
}
and its template:
<p>{{content}}</p>
From another component i would like to (statically) instantiate the component described passing in the content parameter (without the need for binding it). I took the following approach which doesn't work:
<ipe-artboard-layer content="Joep"></ipe-artboard-layer>
<ipe-artboard-layer content="Floris"></ipe-artboard-layer>
<ipe-artboard-layer content="Casper"></ipe-artboard-layer>
Is the approach possible, adviseable? I'd rather not go for a real binding because it's only to instantiate the component with a one-time initial value for some property of it.
Upvotes: 4
Views: 2979
Reputation: 39
EDIT: Don't why it didn't cross my mind initially, but I think that @ViewChild is your way to go. In your parent component .ts declare:
@ViewChild('layer1') layer1: LayerComponent
...
ngAfterViewInit() {
this.layer1.content = 'joey';
}
then in it's template:
<ipe-artboard-layer #layer1></ipe-artboard-layer>
OLD: It doesn't matter if it's initial, one-time or anything. It may be strange for someone coming from plain JS or React, but Input data binding is the Angular way. Alternatively you can use class inheritace with same template, but you'd have to create component for each initial value, which probably is not what you're trying to achieve in long terms.
Upvotes: -1
Reputation: 12342
AFAIK it is not possible to invoke constructor this way.
What you're looking for is @Input()
binding:
<ipe-artboard-layer [content]="Joep"></ipe-artboard-layer>
And in your component:
export class LayerComponent {
@Input()
public content: string;
constructor() {}
}
Here you can read more about component interactions.
Upvotes: 7