Create fields with ngFor

Asked

Viewed 185 times

1

I want to do something where I can every time I click the button to make new fields. What I’ve done is the following:

<label for="">Contatos</label>

<div *ngFor="let contato of contatos" class="row">
    <div class="col-12 col-sm-4 col-md-4">
        <label for="nomeContato">Nome Contato</label>
        <input type="text" class="form-control" aria-label="Default" placeholder="Nome Contato" name="nomeContato" [(ngModel)]="contato['nome']" formControlName="nomeContato">
    </div>
    <div class="col-12 col-sm-4 col-md-4">
        <label for="funcao">Função</label>
        <input type="text" class="form-control" aria-label="Default" placeholder="Função" name="funcao" [(ngModel)]="contato['funcao']" formControlName="funcao">
    </div>
    <div class="col-12 col-sm-4 col-md-4">
        <label for="telefoneContato">Telefone Contato</label>
        <input type="text" class="form-control" aria-label="Default" placeholder="Telefone Contato" name="telefoneContato" [(ngModel)]="contato['telefone']" formControlName="telefoneContato">
    </div>
</div>


<span class="addContact">
    <p (click)="maisContatos()" class="addContactField">+ adicionar mais um(a)</p>
</span>

The HTML where every time I click on p adds more fields

    public maisContatos() {
    this.contatos[this.contador] = {
        nome: '',
        funcao: '',
        telefone: '',
    };
    this.contador++;
}
// Tentei dessas duas formas 
// public maisContatos() {
//     this.contatos.push({
//         nome: '',
//         funcao: '',
//         telefone: '',
//     });
// }

The method I use to add new fields.

So far so good the fields are created and everything seems to work, the problem is that if I fill in the input and add more occurs the following error:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '123'. Current value: ''.
at viewDebugError (core.js:9801)
at expressionChangedAfterItHasBeenCheckedError (core.js:9779)
at checkBindingNoChanges (core.js:9948)
at checkNoChangesNodeInline (core.js:14004)
at checkNoChangesNode (core.js:13976)
at debugCheckNoChangesNode (core.js:14805)
at debugCheckDirectivesFn (core.js:14707)
at Object.eval [as updateDirectives] (ListaProspectosComponent.html:121)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14689)
at checkNoChangesView (core.js:13814)

What I need to do to make it work properly the way I want it to.

  • contatos is a array, then you can add new items to your array, this.contatos.push({nome: '', funcao: '', telefone: ''})

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.