简体   繁体   中英

Angular 5 reactive form valueChanges does not work

I have a form inside a service:

    this.settingsForm = this.formBuilder.group({
        names: this.formBuilder.array([]),
        globalIDs: this.formBuilder.array([]),
        topics: this.formBuilder.array([]),
        emails: this.formBuilder.array([]),
        description: ''
    });

and a getter for convenience-

get description(): FormControl{
    return this.settingsForm.get('description') as FormControl;
}

in some directive I am injecting the service and have a input that attached to this control. html-

<textarea matInput
          [formControl]="settingsDataService.description">
</textarea>

In the directive I have a listener:

 ngOnInit() {
        this.listenToSearchInput();
    }

listenToSearchInput() {
    this.settingsDataService.description.valueChanges.pipe(
        distinctUntilChanged(),takeUntil(this.descriptionDestroy))
        .subscribe(value => {
          //DO SOMETHING
        });
}

but when I am typing in the textarea, my subscriber does not get called.

Maybe it is relevenat- but after listenToSearchInput() is called, in the service after I get an answer from the server I am filling description by-

this.settingsForm.patchValue({description:description});

What can be the reason?

probably you need to call the function in onChanges life cycle hook of your directive.

onChanges(): void {
   this.settingsDataService.description.valueChanges.pipe(
        distinctUntilChanged(),takeUntil(this.descriptionDestroy))
        .subscribe(value => {
          //DO SOMETHING
        });
}

我在从服务器获取数据的函数中找到了答案,我创建了一个新的seetingsForm来清理以前的数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM