klmuralimohan
klmuralimohan

Reputation: 951

Reactive forms setValue from @Input

I would like to do two way binding for reactive form control. Firstly I need to set the value received from @Input data.

Actual result is, when I set static string it is working fine.

Parent component HTML

<ng-template [ngSwitchCase]="'edit'">
          <app-edit class="flex-auto" (editItem)="disciplineAfterView($event)" [discipline] = "selectedItem"></app-edit>
      </ng-template>

Child component HTML

<form [formGroup]="disciplineForm">

      <app-input-multilang [title]="'Discipline'" [form]="disciplineForm" [en]="'discipline_en'" [de]="'discipline_de'">
      </app-input-multilang>

    </form>

Child component TS

 @Input() discipline: any;

this.disciplineForm.get('discipline_de').setValue("dd");  // Working fine

this.disciplineForm.get('discipline_en').setValue(this.discipline.name.en); // Not working

Here the @Input discipline object values

name: {en: "44", de: "44"}

Upvotes: 0

Views: 929

Answers (2)

Vikash B
Vikash B

Reputation: 1005

Try setting the form value inside ngOnChanges()

ngOnChanges(changes: SimpleChanges) {
  if(changes['discipline']) {
    this.disciplineForm.get('discipline_en').setValue(this.discipline.name.en);
  }
}

Upvotes: 1

Franklin Pious
Franklin Pious

Reputation: 3858

Either you can write a setter for the input property and write the setValue once the value is set. Or you can write the setValue inside the ngOnChanges.

ngOnChanges gets called whenever there is a change in the input property.

eg for ngOnChanges.

ngOnChanges(changes: SimpleChanges) {
  if (changes && changes.discipline && changes.discipline.currentValue) {
    this.disciplineForm.get('discipline_en').setValue(this.discipline.name.en);
  }
}

Upvotes: 0

Related Questions