I am creating an array of phone objects where each phone is assigned a role, either main or secondary. I want to be able to update the main phone using a radio button and have it reflect in my object list. Here is my code:
HTML
<section *ngFor="let phone of phoneList; let index = index">
<!-- test 1 -->
<input [checked]="phone.phoneRole==='main'" type="radio" id="phoneTest{{index}}" name="phoneRoleTest">
<!-- test 2 -->
<input [(ngModel)]="phone.phoneRole" type="radio" id="phone{{index}}" name="phoneRole">
<form >
<input id="phoneNumber{{index}}" [disabled]="true" value="{{phone.phoneNumber}}">
<button [disabled]="phone.phoneRole==='main'" (click)="editPhone(phone)">edit</button>
<button type="button" [disabled]="phone.phoneRole==='main'" (click)="deletePhone(phone)">x</button>
</form>
</section>
<form (ngSubmit)="f.form.valid && onAddPhone()" #f="ngForm">
<label for="phoneNumberInput">Phone Number:</label>
<input required class="m-1 col-md-2" type="tel" name="tel" id="phoneNumber" placeholder="Phone number" [(ngModel)]="phoneNumberInput">
<button>+</button>
</form>
Component TS
export class CreateCustomerComponent implements OnInit {
phoneNumberInput: string = '';
phoneList: PhoneNumber[] = [];
phoneIndex: number = 0;
phoneRole: string = 'main';
constructor(private phoneService: PhoneService) {}
ngOnInit(): void {
// set the phoneList from the service to the local phoneList
this.phoneList = this.phoneService.phoneList;
}
create(){
}
onAddPhone() {
// create first obj
if (this.phoneList.length < 1) {
var newPhone = new PhoneNumber(this.phoneNumberInput, this.phoneRole);
} else {
// create new obj phoneNumber
this.phoneRole = 'secondary';
var newPhone = new PhoneNumber(this.phoneNumberInput, this.phoneRole);
}
// add phoneNumber to phoneList
this.phoneService.addPhone(newPhone);
}
editPhone(phone: PhoneNumber) {
if (phone.phoneRole === 'main') {
alert('No editable');
} else {
}
}
deletePhone(phoneNumber: PhoneNumber) {
this.phoneService.delete(phoneNumber);
}
}
Service TS
import { PhoneNumber } from "./phoneNumber.component";
export class PhoneService{
phoneList: PhoneNumber[]=[];
addPhone(newPhone:PhoneNumber){
// add phoneNumber to phoneList
this.phoneList.push(newPhone);
};
delete(phoneNumber: PhoneNumber){
// delete phoneNumber of the phoneList
const index: number = this.phoneList.indexOf(phoneNumber);
this.phoneList.splice(index,1);
};
}
I would like to know if it is possible to set the main phone in my objects array using a radio button. Thank you for your time!