Search code examples
angularinputangular4-formsngmodel

Angular Two-Way-Databind - Change Value


I Have one Form with an input.

<form #modelContrato="ngForm" role="form" >
<input [(ngModel)]="modelContrato.numero" id="numero" class="form-control" name="numero" type="text" autocomplete="off" placeholder="Número Contrato"
                                        #numero="ngModel" required />

On my component.ts I have these lines.

@Input() modelContrato: Contrato;

On Constructor

this.modelContrato = {} as Contrato;

ngOnInit

this.modelContrato.numero = '10';

ps: Contrato is a model. Like This

export interface Contrato {
    id: string;
    contratoPrincipalId: string;
    numero: string;
}

Why my input not change de value passed in OnInit ?


Solution

  • Generic solution: work with @ViewChild to refer to an Element. https://angular.io/api/core/ViewChild

    Your personal problem solution: just create a field in your component

    const modelContrato: Contrato;

    since the [(ngModel)]="modelContrato.numero" two-way binds to the modelContrato numero attribute to the input-element value

    Why your Code wont work: you misstook the input Element to be bound to @input decorator. The @input Decorator is for passing properties from ancestor to successor Components. https://angular.io/guide/component-interaction