首页 > 解决方案 > 即使在更改@Input 布尔值后,NgOnChanges 也不会触发?

问题描述

我是 Angular 新手,已经看到了各种答案,但无法解决。我正在使用 Angular 11。这是我的代码:

    @Component({
      selector: 'app-custom-quill-editor',
      templateUrl: './custom-quill-editor.component.html',
      styleUrls: ['./custom-quill-editor.component.css'],
    })
    export class CustomQuillEditorComponent implements OnInit, OnChanges {
      static textChange() {
        throw new Error('Method not implemented.');
      } 
      quill1: any;
       data: any[] = [new Temp()];
       @Input() flag:boolean=false;
      constructor(private getDataService: GetDataService) {   
      }
    ngOnChanges(changes:SimpleChanges){
    console.log("In ng changes");
 console.log(changes);
let tdelta = {
      ops: this.data,
    };
    var Delta = Quill.import('delta');
    //let editor = new Quill('#editor');  // finding quill editor with id editor
    const delta = new Delta(tdelta);
    //editor.setContents( delta ,'api');
    var quill = new Quill('#editor-container', {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline'],
          ['blockquote'],
          [{ header: 1 }, { header: 2 }],
          [{ list: 'ordered' }, { list: 'bullet' }],
        ],
      },
      placeholder: 'Compose an epic...',
      theme: 'snow', // or 'bubble'
    });
    this.quill1 = quill;
    this.quill1.updateContents(delta, 'api');
    //trigerring these events if text is changed in editor
    quill.on(
      'text-change',
      this.textChange
    );
  }
    }
 ngOnInit(){
    this.getDataService.getJSON().subscribe((fetchedData) => {
      console.log('Fetched data in component');
      console.log(fetchedData);
      console.log("data before assigning it to fetchedData");
      console.log(this.data);
      this.data=fetchedData;
      console.log(this.flag);
      this.flag=!this.flag;
      console.log(this.flag);
      //this.cd.detectChanges();

      console.log("data after assigning it to fetchedData");
      console.log(this.data);
      console.log('Final data array');
      console.log(this.data);

    });
  }

在控制台中,我可以看到变量标志的值发生了变化,但仍然没有触发 ngOnChnages。有没有其他方法可以做到这一点?

标签: angular

解决方案


为什么不在输入中使用设置器?

_private flag
@Input set flag(value){
   this._flag=value;
  ...do something...
}

get flag()
{
   return this._flah
}

推荐阅读