Does child component re-render or re-initialize in Angular?

Discussão em 'Angular' iniciado por Alok Shaw, Outubro 14, 2024.

  1. Alok Shaw

    Alok Shaw Guest

    I am new to Angular(14) and i am facing a issue. when i update a property of parent component which is an array then the child component get re-initialize(ngOnInit function is running). Facing this issue when using child component in a for loop.

    // parent Component ts file
    students: string[] = ['student1', 'student2', 'student3', 'student4'];
    updateName(value: string, index: number) {
    console.log(index);
    this.students[index] = value;
    }
    // template of Parent component
    <app-search
    *ngFor="let student of students; let i = index"
    [student]="student"
    (changeName)="updateName($event, i)"
    >

    // Child component ts file
    searchValue = '';
    @Input() student!: string;
    @Output() changeName = new EventEmitter<string>();
    updateName() {
    this.changeName.emit(this.searchValue);
    }
    // template of Child component
    <div class="search-container">
    <span>
    Search:
    </span>
    <input type="text" [(ngModel)]="searchValue">
    <p>{{searchValue}}</p>
    <p>Student Name: {{student}}</p>
    <button (click)="updateName()">Update</button>
    </div>


    when i am updating a name input field is getting blank. I write this code just to understand how it work(i know there migth not be any use of this kind of code). Facing this issue when using child component in a for loop.

    It would be good if i get any reference of this.

    Continue reading...

Compartilhe esta Página