JBoy
JBoy

Reputation: 5735

Angular 'property used before its initializadion' on @input object

in my component i have a variable which is populated by the parent module, one of this variable's field 'description' should be displayed in the html template with a two way binding textarea so i can edit it:

   @Input() table: Table;
   public tableDescription: String = this.table.description (does not compile)

The above code wont compile, i get a angular property is used before its initialization error. The way i am using that variable in the template is:

    <form class="form-table-description">
       <mat-form-field class="mat-table-description-input" appearance="fill">
       <textarea matInput style="resize: none;" rows="7" id="tableDescription" name="tableDescription" [(ngModel)]="tableDescription">{{tableDescription}}</textarea>
        </mat-form-field>
        <mat-button-toggle (click)="updateDescription()">Update description
</mat-button-toggle>
</form>

I have also tried to initialize that variable in ngOnInit:

ngOnInit() {
        this.tableDescription = this.table.description
    }

But although the code compiles i see:

How can i initialize the tableDescription variable in the component with the value of table.description and display it in the html template?

Upvotes: 1

Views: 1318

Answers (2)

Anton Marinenko
Anton Marinenko

Reputation: 2982

You have to know when @Input() is changed to be sured you have table property set.

So this is better solution to ngOnChanges, it invokes only on @Input changed:

@Input set table(value: Table) {
  this.tableDescription = value?.description;
}

Upvotes: 0

Antoniossss
Antoniossss

Reputation: 32517

You have to move this assignment to at least ngOnInit() and the best would be ngOnChanges to react to input changes.

  @Input() table: Table;
   public tableDescription:string;

ngOnChanges(changes:SimpleChanges){
   if(changes.table){
       this.tableDescription= this.table?.description;
    }
    
}

Upvotes: 2

Related Questions