我有3个按钮let link of links
links = [
{
name: "Link 1",
id: "number1"
},
{
name: 'Link 2',
id: "number2"
}
{
name: "Link 3",
id: "number3"
}
]
他们以HTML格式渲染3个按钮。
我有一个DIV,“让卡号为1”:
number1 = [
{
name: 'IT',
address: 'Tokyo 4',
},
{
name: 'Computer',
address: 'Tokyo 4',
},
{
name: 'Garden',
address: 'Tokyo 4',
},
{
name: 'Cars',
address: 'Tokyo 4',
}
]
他们用D {{ card.name }}
和P {{ card.address }}
但是,当我点击第2个按钮时,如何将let card of number1
更改为let card of number2
?
像这样:
(click)="change number1 to number2" - when I click button number 2 etc
PLUNKER: https://plnkr.co/edit/MfSx9MjoVtHprFtBHKDZ?p=preview
答案 0 :(得分:0)
指向不同的数组变量并在按钮单击时切换引用。 This is your plunker这样做。
//our root app component
import {Component, NgModule, OnInit, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<li *ngFor="let link of links">
<button (click)="updateLinks(link.id)">{{ link.name }}</button>
</li>
<div *ngFor="let card of numbers">
<h1>{{ card.name }}</h1>
<p>{{ card.address }}</p>
</div>
`,
})
export class App implements OnInit {
numbers: any[];
ngOnInit(){
this.numbers = this.number1;
}
updateLinks(linkId: string){
this.numbers = this[linkId] as any[];
}
links = [
{
name: "Link 1",
id: "number1"
},
{
name: 'Link 2',
id: "number2"
}
{
name: "Link 3",
id: "number3"
}
]
number1 = [
{
name: 'IT',
address: 'IT Number 1',
},
{
name: 'Computer',
address: 'Computer Number 1',
},
{
name: 'Garden',
address: 'Garder Number 1',
},
{
name: 'Cars',
address: 'Cars Number 1',
}
]
number2 = [
{
name: 'IT',
address: 'IT Number 2',
},
{
name: 'Computer',
address: 'Computer Number 2',
},
{
name: 'Garden',
address: 'Garder Number 2',
},
{
name: 'Cars',
address: 'Cars Number 2',
}
]
number3 = [
{
name: 'IT',
address: 'IT Number 3',
},
{
name: 'Computer',
address: 'Computer Number 3',
},
{
name: 'Garden',
address: 'Garder Number 3',
},
{
name: 'Cars',
address: 'Cars Number 3',
}
]
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
答案 1 :(得分:0)
您可以创建多个按钮并有条件地显示/隐藏它们吗?
<button *ngIf="arrayNumber === 1" (click)="myFirstFunction()"></button>
<button *ngIf="arrayNumber === 2" (click)="mySecondFunction()"></button>
答案 2 :(得分:0)
另一种方法:
<强> HTML:强>
<li *ngFor="let link of links; let i = index">
<button (click)="setNumber(i)">{{ link.name }}</button>
</li>
<强>打字稿:强>
...
number;
....
constructor(){
this.number=this.number1
}
...
setNumber(index){
console.log(index)
switch(index){
case 0:
this.number = this.number1;
break;
case 1:
this.number = this.number2;
break;
case 2:
this.number = this.number3
}
}
<强> DEMO 强>