Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

javascript - Not able to pass string to formGroup

1.I want to loop through an array

*ngFor="let item of myformNameArray"

Think myformNameArray.length have 3 items If I console item it will be like

myFormName1
myFormName2
myFormName3

I have already made these form group in my typescript component.

Example

<form [formGroup]="myFormName3">

It will work perfectly!!

But i want to loop :means

<div *ngFor="let item of  myformNameArray">
<form [formGroup]="{{item}}">
</form>
</div>

So when I do,

[formGroup]="{{item}}"

It throws me an error can't assign to object or interpolation

Or

[formGroup]="see(item)"

Where ,

see(item) :string {
return String(item);
}

ERROR TypeError: can't assign to property "validator" on "see(item)": not an object

question from:https://stackoverflow.com/questions/65930219/not-able-to-pass-string-to-formgroup

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[formGroup] requires a FormGroup Object not string

you need to make array of formgroups instead of string names

TS:

myformArray = [
   this.myFormOne,
   this.myFormTwo,
   this.myFormThree
]

HTML:

<div *ngFor="let item of  myformArray">
    <form [formGroup]="item">
    </form>
</div>

you can also use formArray instead of normal array

TS:

myFormArray = new FormArray([]);

this.myFormArray.push(myFormOne);
this.myFormArray.push(myFormTwo);
this.myFormArray.push(myFormThree);

HTML:

<div *ngFor="let form of myFormArray.controls;">
  <form [formGroup]="form">
    <input formControlName="controlOne" />
    <input formControlName="ControlTwo" />
  </form>
</div>

And also you should not use both square brackets and curly brackets (interpolation) for property binding, use either square brackets or interpolation.

internally angular converts square brackets to interpolation

either do this : [formGroup]="item" or this : formGroup="{{item}}"

not both


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...