在阅读了与该主题相关的多个主题之后,我正在写这篇文章,但是没有人给我我所需要的。这篇文章似乎有解决方案,但我不必从json中读取已检查的值。
我需要做的是:
用户应选中并取消选中每个复选框
奖金:
我知道这可能确实很愚蠢,但是直到现在我所要做的就是拥有一系列不可检查的复选框,仅此而已。
这是代码:模板:
<div class="form-group">
<div *ngFor="let country of countries">
<input type="checkbox"
name="countries"
value="{{country.id}}"
[(ngModel)]="country"/>
<label>{{country.name}}</label>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
和TS:
countries = [
{id: 1, name: 'Italia'},
{id: 2, name: 'Brasile'},
{id: 3, name: 'Florida'},
{id: 4, name: 'Spagna'},
{id: 5, name: 'Santo Domingo'},
]
Run Code Online (Sandbox Code Playgroud)
我试图使用反应形式,但这给了我更多的问题,然后是模板驱动的(肯定是因为我的实现不好)。拜托,帮帮我,我不知道该撞到哪里了
这是一个工作示例,您可以在其中观察到一个附加的“已检查”值添加到每个国家/地区,并使用绑定到每个复选框的值[(ngModel)]。
模板:
<p>
Test checkboxes
</p>
<div *ngFor="let country of countries; let i = index;">
<input type="checkbox" name="country{{country.id}}" [(ngModel)]="countries[i].checked">
<label for="country{{country.id}}">{{country.name}}</label>
</div>
<button type="button" (click)="sendCheckedCountries()" *ngIf="countries">Click to send the selected countries (see your javascript console)</button>
<p *ngIf="!countries">loading countries, please wait a second...</p>
<p *ngIf="countries">Debug info : live value of the 'countries' array:</p>
<pre>{{ countries | json }}</pre>
Run Code Online (Sandbox Code Playgroud)
零件 :
//...
export class AppComponent implements OnInit {
public countries: Country[];
constructor(private countryService: CountryService) {}
public ngOnInit(): void {
// loading of countries, simulate some delay
setTimeout(() => {
this.countries = this.countryService.getCountries();
}, 1000);
}
// this function does the job of sending the selected countried out the component
public sendCheckedCountries(): void {
const selectedCountries = this.countries.filter( (country) => country.checked );
// you could use an EventEmitter and emit the selected values here, or send them to another API with some service
console.log (selectedCountries);
}
}
Run Code Online (Sandbox Code Playgroud)
为了使用适当的TypeScript,我创建了一个Country界面:
interface Country {
id: number;
name: string;
checked?: boolean;
}
Run Code Online (Sandbox Code Playgroud)
希望您现在就明白。
注意:选中的值在开始时并不是“自动存在”的,但这无关紧要。
如果不存在,则与相同undefined,并且false在复选框和读取已检查国家/地区的函数中均将其视为 。
对于“发送价值”部分:
该按钮会将选定的值输出到浏览器的控制台,并带有类似于@Eliseo的答案建议的过滤器(我只是使用完整的国家/地区对象而不是ID)
对于“真实用例”情况,您可以使用Angular的EventEmitters并将组件的值“发射”给父组件,或者调用一些服务函数,以将值的请求发送给另一个API。
| 归档时间: |
|
| 查看次数: |
12277 次 |
| 最近记录: |