![](/img/trans.png)
[英]Angular - How to bind textarea input to image in the loop using form
[英]How to bind two arrays using Input/Output Angular?
一個組件(通過@Input())獲得2個數組:“用戶”
[{Id: 1, Name: 'One'}, {Id: 2, Name: 'Two'}, {Id: 3, Name: 'Three'}]
和“ selectedUsers”:
[{Id: 2, Name: 'Two'}]
並在頁面上輸出項目:一二三
“ Two”-突出顯示,因為它包含在數組“ selectedUsers”中。 如何通過單擊將項目從“用戶”數組添加到“ selectedUsers”,反之亦然(並突出顯示單擊的項目)?
父組件:
users = [
{Id: 1, Name: 'One'},
{Id: 2, Name: 'Two'},
{Id: 3, Name: 'Three'}
];
usersSelected = [
{Id: 2, Name: 'Two'}
];
HTML:
<app-item (*ngFor="let u of users", [user]="u")></app-item>
子組件:
@Input() user;
isActive: boolean = false;
toggleClass(){
this.isActive = !this.isActive;
}
的HTML
<p [class.active]="isActive" (click)="toggleClass()">{{user.Name}}</p>
這是另一種嘗試,但是應該使用@ Input / @ Output來完成: https : //plnkr.co/edit/cjaij4aQuvN4Tk4ZE0ez?p=preview
為什么需要2個數組? 只需使用名為boolean
(true / false)類型的selected
屬性擴展用戶類型。 這樣可以更清潔/輕松地使用,然后在兩個陣列之間復制/刪除用戶。
users = [
{Id: 1, Name: 'One', IsSelected: false},
{Id: 2, Name: 'Two', IsSelected: true},
{Id: 3, Name: 'Three', IsSelected: false}
];
這允許用於在數組中呈現用戶的任何組件直接更新IsSelected
屬性。
@Input() user;
get isActive(): boolean {return this.user.IsSelected;}
toggleClass(){
this.user.IsSelected = !this.user.IsSelected;
}
另外我也不認為這是您的html中有效的模板語法。
如果您想使用兩個數組以及一個父子組件:
https://plnkr.co/edit/uEKeMRMpLnoR49clxCfo?p=preview
@Component({
selector: 'my-parent',
template: `
<my-child [users]="users" [selected]="selected" ></my-child>
`,
})
export class ParentComponent {
public users = ['one', 'two', 'three' ];
public selected = [];
}
@Component({
selector: 'my-child',
template: `
<div *ngFor="let user of users">
<p [ngClass]="{ selected: isSelected(user) }" (click)="clickOnUser(user)">{{user}}</p>
</div>
`,
styles: [`
.selected {
color: red;
}
`]
})
export class ChildComponent {
@Input()
public users: string[];
@Input()
public selected: string[];
public isSelected(user) {
return this.selected.indexOf(user) !== -1;
}
public clickOnUser(user) {
if (this.selected.indexOf(user) !== -1) {
this.selected.splice(this.selected.indexOf(user), 1);
} else {
this.selected.push(user);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.