Angular 4 - using objects for option values in a select list

后端 未结 6 1032
南旧
南旧 2020-12-23 20:25

I know that similar questions have been asked, but I\'ve found none with a good answer. I want to create a select list in an Angular form, where the value for each option is

6条回答
  •  一整个雨季
    2020-12-23 20:42

    As value attribute of option tag cannot store a whole object we will create a new property id in the lUsers array to keep track of the selected item.

    HTML :

    
    

    This will pass the unique id to our setNewUser function on change.

    In your component.ts :

    ...
    
    lUsers: any[] = [
        { id: 1, Name: 'Billy Williams', Gender: 'male' },
        { id: 2, Name: 'Sally Ride', Gender: 'female'}
    ];
    curUser: any = this.lUsers[0]; // first will be selected by default by browser
    
    ...
    
    setNewUser(id: any): void {
        console.log(id);
        // Match the selected ID with the ID's in array
        this.curUser = this.lUsers.filter(value => value.id === parseInt(id));
        console.log(this.curUser);
    }
    

    Here is the plnkr demo of the above code. Open your developer tools to view the console logs.

提交回复
热议问题