Angular2 - how to setup radio button option to use a dynamic value

886 views Asked by At

I have a Proposal component where the user selects a value from a radio button:

  public salutations = [
    { value: 0, display: 'Mr & Mrs' },
    { value: 1, display: 'Mrs' },
    { value: 2, display: 'Ms'},
    { value: 3, display: 'Mr'},
    { value: 4, display: 'proposal.first_name'}
  ];

In each case, the selected option is stored in the Proposal.greeting field. I don't store the value, but the actual display property.

  <div *ngFor="let salutation of salutations">
    <label>
      <input type="radio" name="salutation" [(ngModel)]="proposal.salutation" 
        [value]="salutation.display"> <!-- we DO NOT want to store the integer value -->
        {{salutation.display}}
    </label>
  </div>

As you can see, when the user selects option 4, the intention is to store the actual name of the proposer (proposal.first_name).

This is because later I have a view that looks like this:

<p>Dear {{proposal.greeting}} {{proposal.last_name}},</p>

So how can I make that option 4 dynamic (so that when selected it stores the first_name and not the string 'proposal.first_name').

1

There are 1 answers

2
Elliott Beach On BEST ANSWER

You need to get rid of the quotes around proposal.firstname in your TypeScript. Because salutations is declared in a .ts file, not html, Angular is not going to perform interpolation. Also, you need to tack on a this. prefix.

public salutations = [
    { value: 0, display: 'Mr & Mrs' },
    { value: 1, display: 'Mrs' },
    { value: 2, display: 'Ms'},
    { value: 3, display: 'Mr'},
    { value: 4, display: this.proposal.first_name} 
  ];

See the plunkr I put together.