netdjw
netdjw

Reputation: 6007

How can I force the name property on the input fields in Angular 9?

I'm trying to switch off autofill Chrome built-in function in my Angular 9 app. I found the Chrome attach the autofill suggestions to the name of the input field.

I have this Angular 9 HTML code:

<input
  [class]="inputClass"
  [(ngModel)]="model[field]"
  [id]="field"
  [name]="field + '_' + random"
  [placeholder]="getPlaceholder()"
  [disabled]="disabled"
  [type]="type"
  [autocomplete]="random"
  (keyup)="validateField()">

And I get this in the generated HTML code if I run the app:

<input
  _ngcontent-cbv-c111=""
  class="form-control ng-pristine ng-valid ng-touched"
  ng-reflect-model=""
  id="name"
  ng-reflect-name="name_6xuz5"
  placeholder="My placeholder"
  type="text"
  autocomplete="6xuz5">

Now here isn't a name property on input tag. And that's because I use this syntax: [name]="...". If I use the name="..." syntax then the name property will be presented.

How can I force the name property on the input fields and still use the [name]="..." syntax to give a calculated value?

Upvotes: 0

Views: 1411

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20043

Using [name] tells Angular that this is a property binding (like an input), but you want to set an HTML attribute. For this you can instead use

<input [attr.name]="field + '_' + random" …>

which tells Angular that you want to set it as an attribute.

Alternatively, you can also use

<input name="{{ field + '_' + random }}" …>

but arguably that doesn't look as pretty.


This is a bit confusing in Angular, and there are plans to at least improve the documentation, see this.

Upvotes: 2

Related Questions