javascript - @Input özelliği ikinci kez güncellenmiyor


Herhangi bir dış bileşenden gösterilebilecek yeniden kullanılabilir bir bileşen oluşturuyorum, ancak aynı bileşendeki bir fonksiyonla gizlenebilir, ama bir şekilde üst bileşendeki özellik değişikliği alt bileşeni güncellemiyor.

İşte bunun için stackblitz. https://stackblitz.com/edit/angular-hfjkmu

Benim ihtiyacım olan, "Göster" butonunun bileşeni her zaman göstermesi ve "gizle" butonunu kullanarak bileşeni istediğim zaman gizleyebilmem.

Cevap #1

çocuğun değerini ebeveyne Output kullanarak senkronize etmeniz gerekiyor

  @Input()
  show = false;

  @Output()
  showChange = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit() {
  }

  hide(){
    this.show = false;
    this.showChange.emit(this.show);
  }
<app-show-hide [(show)]="show"></app-show-hide>

Çocuk bileşenden gelen show özelliği, üstün bileşendeki aynı özelliğe işaret etmiyor, çünkü bu bir ilkel değerdir. Çocuğa ait olmayan verileri (referans tipi, örn: nesne, dizi) değiştirmeyi önermiyorum, bu beklenmeyen davranışlara yol açabilir.

Referans türü ile çevrimiçi demo (ref türünü değiştirdiğinizde dikkatli olun): https://stackblitz.com/edit/angular-vhxgpo?file=src%2Fapp%2Fshow-hide-obj%2Fshow-hide-obj.component.tsenter link description here

Cevap #2

Sorununuz, alt bileşeninizin Input değerini kendi alt bileşen kapsamı içinde değiştirmesi nedeniyle ortaya çıkıyor, bu yüzden üst bileşenin verinin değiştiğini bilmesinin bir yolu yok.

Çocuk bileşeniniz

   export class ShowHideComponent implements OnInit {
      @Input('show') show: boolean;
      @Output() updateShowValue: EventEmitter<any> = new EventEmitter<
        any
        >();
      constructor() { }

      ngOnInit() {
        console.log(this.show);
      }

      hide() {
        this.updateShowValue.emit(!this.show);
      }
    }

app.component.html dosyasında

<app-show-hide [show]="show" (updateShowValue)="update($event)"></app-show-hide>

Ve app.component.ts

export class AppComponent implements OnInit {
  show:boolean = false;
  ngOnInit() {
    this.show = false;
    console.log(this.show)
  }
  showComp(){
    this.show = !this.show;
  }

  update(event) {
    this.show = event;
  }
}

İlgili makaleler