'How to pass element ID from one component to another in Angular?
before asking the question i have find few similar question on stack overflow about the problem i'm facing. i'm trying to pass ID from one template to another. my first template looks like this
<View
[id] = "'some_id'"
[Behavior] = "behavior"> </View>
in my second template i have this.
<canvas id="id"></canvas>
to move data from one component to another i'm using @input decorators. works fine. inside the first component i have to create object of second component. in both components i'm using ngOnInit methods, first one creates objects, second one initializes them. problem starts here, when creating object it do not have id yet. its undefined.
this.obj= MyObj.create(document.querySelector('#some_id'))
i have used @Input, AfterViewInit, OnChanges, *ngIf to force somehow id not to be null or undefined. but failling. can anyone give me a good advice how to assing id from one template to another?
Solution 1:[1]
When you are passing a string with data binding it means you are assigning constant string some_id to id inside children component.
[id] = "'some_id'"
In below, you are binding the parent component class property some_id to the id Input property of children component.
[id]="some_id"
Solution 2:[2]
When you say [id] = "'some_id'", the input variable is actually id. 'some_id' is the value of that input variable.
Try the following
child.component.ts
@Input() id: string;
child.component.html
<canvas id="id"></canvas>
Update
May be calling a custom input variable the same as a built-in property is doing something unintended. Try using other name
child.component.ts
@Input() customId: string;
child.component.html
<canvas id="customId"></canvas>
parent.component.html
<app-child [customId]="'some_id'"...></app-child>
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 | Jasdeep Singh |
| Solution 2 |
