I've been using angular for a while. I want to implement two way binding but I'm stuck with the following code.
Since [(ngModel)]
is no no longer used in angular 12 within the formGroup
I'm unable to find a solution
socials = [
{ name: 'Facebook', icon: 'facebook.webp', selected: false, link:'' },
{ name: 'Instagram', icon: 'instagram.webp', selected: false, link:'' },
{ name: 'Twitter', icon: 'linkdin.webp', selected: false, link:'' },
{ name: 'Whatsapp', icon: 'whatsapp.webp', selected: false, link:'' }
];
here I want to change the value of link that will be entered in the following input (6th last line)
<div >
<div *ngFor="let control of socialsArray.controls; let i = index;">
<input type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" id="checkbox{{i}}">
<label for="checkbox{{i}}" >
<div [ngStyle] = "{'background-color' : socials[i].selected == true ? '#ededed' : '#fff'}">
<div >
<fa-icon [icon]="faCheckCircle" [ngClass]="socials[i].selected === true ? 'iconColor' : 'iconColor1'"></fa-icon>
</div>
<div >
<div >
<img src="/assets/images/social_media/{{socials[i].icon}}" width="40px" height="40px"
>
</div>
<div >
<div>
{{socials[i].name}}
</div>
</div>
</div>
</div>
<div [ngStyle] = "{'display' : socials[i].selected == true ? 'block' : 'none' }">
<div >
<label>
{{socials[i].name}} link
</label>
<input type="text" (change)="getSelectedSocialsCards()" formControlName="socialLink">
</div>
</div>
</label>
</div>
</div>
I've declared socialLink
inside formGroup
socialLink:new FormControl(null, [Validators.required])
this is my component.ts code for the same
getSelectedSocialsCards() {
this.selectedSocialsCards = [];
this.socialsArray.controls.forEach((control, i) => {
this.socials[i].selected = false;
if (control.value) {
this.socials[i].selected = true;
this.socials[i].link = this.addForm.get('socialLink').value;
let linksValue = {'socialName': this.socials[i].name, 'socialLink': this.socials[i].link}
this.selectedSocialsCards.push(linksValue);
}
});
console.log(this.selectedSocialsCards);
this.socialError = this.selectedSocialsCards.length > 0 ? false : true;
this.addForm.patchValue({socialsCheck: this.selectedSocialsCards});
}
So far I'm able to get the last value inserted intot he input field and that is the value of all the links.
I've tried to resolve the issue but couldn't find any solution. I'll be obliged if anyone can help me with this. Thank you
CodePudding user response:
You can use [(ngModel)] in within the formGroup mention 'name' in tag. for example <input type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" [(ngModel)]="testcontrol" name="testcontrol" id="checkbox{{i}}"> like that