Angular 2 forms dynamic id and for attributes
Solution 1
Seems that the problem was how the input was bound where the component was used. So given the component in the question the following doesn't work:
<hello id="hello"></hello>
But instead the input has to be bound with brackets:
<hello [id]="'hello'"></hello>
Seems that this is because the conflict with native id attribute. If I rename the input to something else the first style also works.
<hello identifier="hello"></hello>
@Input() identfier: string;
Solution 2
It does work. Check out the demo. You might be missing the correct property values in your component class.
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
id = 'hello';
label = 'hello';
model = 'one';
}
app.component.html
<label [attr.for]="id">{{label}}</label>
<input [(ngModel)]="model" [attr.id]="id">
Related videos on Youtube
Antti Väyrynen
Updated on June 04, 2022Comments
-
Antti Väyrynen almost 2 years
I have a problem creating a link between the
label
andinput
element in angular withfor
andid
attributes. Given the following code:@Component({ selector: 'hello', template: ` <label [attr.for]="identifier">{{label}}</label> <input [(ngModel)]="model" [attr.id]="identifier"> `, }) export class HelloComponent { @Input() identifier: string; }
What I want is to be able to focus the input field by clicking the label, which is the default behavior in web. This behavior works if I set the attributes statically. Or if I manually update the attributes in DOM from developer tools.
What I have tried, for both
id
andfor
:id="{{identifier}}" [id]="identifier" [attr.id]="identifier"
UPDATE
Found out the problem. Check the answer below.
-
Boanta Ionut about 6 yearsI am pretty sure you need the input first then the label. You can then set their style in css, but html does not render the input at the time you set the for id.
-
Antti Väyrynen about 6 yearsDoesn't solve the problem, and puts them visually the wrong way around.
-
-
Antti Väyrynen about 6 yearsI forgot the mention that the id variable is an angular component input. The example you gave does work. I edited the original question.
-
Tomasz Kula about 6 yearsIt does not change anything. Just decorate the id property with an
@Input
decorator.[attr.for]
and[attr.id]
are property binding so angular will update them accordingly. -
Tomasz Kula about 6 years@AnttiVäyrynen I've updated the demo to use
@Input
id and it still works just fine. Take a look. -
Antti Väyrynen about 6 yearsFound out the problem, check my own answer.