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

后端 未结 6 1005
南旧
南旧 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:50

    I'm currently using [ngValue] and it stores objects just fine.

    The explanation as to why you experienced issues using (change) instead of (ngModelChange) can be found in this question

    So, since you've already used [ngValue], you probably want to do something like this, where you will only use one way binding in order to be able to use the ngModelChange directive:

    
    

    And your ts file will capture the event and receive the User object without needing to track it by id, basically reusing your old method will be good enough:

    setNewUser(user: User): void {
        console.log(user);
        this.curUser = user;
        }
    

    UPDATE 16/06/2020:

    Always depending on your use case you may need to use square brackets instead of round here: (ngModel)="lUsers. For the particular case the OP stated, round brackets was the right choice. A clear and detailed description of the difference between square/round and banana box can be found in this answer from Angular guru Günter Zöchbauer

提交回复
热议问题