'Pass parameter to constructor from template

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1