比如我又一個陣列如下:
var array = ['喜欢','不喜欢','非常喜欢','超级喜欢','喜欢得不得了'];
html模板中
<p class="like" *ngFor="let e of array">
<input type="checkbox" name="like" value="{{e}}">
</p>
<p class="youselect"></p>
我蓋如何實現,選中其中一個checkbox後,能在p.youselect中顯示出我已經選中的內容,如果是多選,則呈現出數組或者以逗號隔開的形式
例如我選了“喜歡”,“喜歡得不得了”,那麼p.youselect中則顯示出:
“喜歡,喜歡得不得了”
可以使用formArray等方式進行,但是我在使用過程中都沒有實作。希望大神出手幫忙!
我想大声告诉你2017-06-26 10:57:43
謝邀,基於你給的資料結構,但建議還是使用如下資料結構(表單提交的時候,一般提交的對應的id項):
[
{ name: '喜欢', selected: true, id: 0 },
{ name: '不喜欢', selected: false, id: 1 }
]
具體可以參考 - handling-multiple-checkboxes-in-angular-forms
簡單的範例程式碼如下:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="myForm">
<p class="like" *ngFor="let like of likes.controls; let i = index;" >
<input type="checkbox" [formControl]="like">
{{likesArr[i]}}
</p>
<p class="youselect">{{selects}}</p>
</form>
`,
})
export class AppComponent implements OnInit{
myForm: FormGroup;
likesArr: string[] = ['喜欢','不喜欢','非常喜欢','超级喜欢','喜欢得不得了'];
selects: string[] = ['喜欢'];
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
likes: this.fb.array([true, false, false, false, false])
});
this.likes.valueChanges.subscribe(values => {
let selects: string[] = [];
values.forEach((selected: boolean ,i: number) => {
selected === true && selects.push(this.likesArr[i])
});
this.selects = selects;
});
}
get likes () {
return this.myForm.get('likes');
}
}
欧阳克2017-06-26 10:57:43
個人感覺不用 Forms 好像更簡單吧。 。 。
寫了一個 Fiddle: https://jsfiddle.net/phnjg6hf/4/
HTML:
<test-component></test-component>
<script id="some" type="text/plain">
<p>Result: {{result()}}</p>
<p *ngFor="let w of arr">
<label>
<input type="checkbox" value="{{w}}" [checked]="selections[w]" (change)="handle($event)" />
{{w}}
</label>
</p>
</script>
JS:
var Thing = ng.core.Component({
selector: "test-component",
template: document.getElementById("some").innerHTML
})(function () {
this.selections = { First: true };
this.arr = ["First", "Second", "Third"];
});
Thing.prototype.result = function () {
var that = this;
return this.arr.filter(function (x) {
return that.selections[x];
}).join(", ");
};
Thing.prototype.handle = function (e) {
var t = e.target, v = t.value, c = t.checked;
this.selections[v] = c;
};
var AppModule = ng.core.NgModule({
imports: [ng.platformBrowser.BrowserModule],
declarations: [Thing],
bootstrap: [Thing],
providers: []
})(function () { });
ng.platformBrowserDynamic.platformBrowserDynamic().bootstrapModule(AppModule);