Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - Observable - set first value of Observable into formgroup

I do have an Observable of Contacts in my onInit method and I also will set the first contact of the Observable into my form. Has anyone a hint how to do this?

ngOnInit() { 
    let contactsObservable: Observable<Contact[]> = 
    this.contactService.getAllContacts();
    contactsObservable.subscribe(contacts => {
        this.contacts = contacts; 
    });

    this.form = this.fb.group({ 
                // this.contacts[0] does not work
      contact: [this.contacts[0], [Validators.required]] // how to get contact[0] into form for presetting
    });
}
like image 680
quma Avatar asked Mar 07 '23 18:03

quma


1 Answers

You get contacts async. Value can be put when Observable return value.

ngOnInit() { 
   this.form = this.fb.group({ 
     contact: ['', [Validators.required]] 
   });
   let contactsObservable: Observable<Contact[]> = 
   this.contactService.getAllContacts();
   contactsObservable.subscribe(contacts => {
       this.contacts = contacts; 
       this.form.controls['contact'].setValue(this.contacts[0])
   });
}
like image 53
ambussh Avatar answered Mar 31 '23 06:03

ambussh