将字符串的方法插入到2d数组Angular 4中

时间:2018-03-19 09:04:42

标签: html arrays angular typescript ngfor

我正在尝试创建一个网页,在这个页面中,我需要在第6列的图像中显示他们的名字和描述。但我一直试图展示他们的名字和描述。这是我的代码:

component.ts

 export class TeamComponent implements OnInit {
 public team: any[][];
 title = ' Team ';
 name: string;
 description: string;

constructor() {
this.team = [
  [this.firstTeamMember(), this.secondTeamMember()],
  [this.thirdTeamMember(), this.fourthTeamMember()],
  [this.fifthTeamMember(), this.sixthTeamMember()]
 ];
}

firstTeamMember(): {
this.name = 'A name';
this.description = 'text';
}

secondTeamMember(): {
this.name = 'Another name';
this.description = 'text';
}

thirdTeamMember(): {
this.name = 'Another name';
this.description = 'text';
}

fourthTeamMember(): {
this.name = 'Another name';
this.description = '...';
}

fifthTeamMember(): {
this.name = 'Another name.';
this.description = 'text';
}

sixthTeamMember(): {
this.name = 'Another name';
this.description = 'text';
}

component.html

<h1>{{ title }}</h1>
<div class="team" *ngFor="let i of team">
<span *ngFor="let j of i">
{{j}}
</span>
</div>

2 个答案:

答案 0 :(得分:0)

我认为你应该使用对象而不是函数

firstTeamMember = {
    name: 'Another name',
    description:'text'
}

然后你的数组看起来像这样

constructor() {
    this.team = [
        [this.firstTeamMember, this.secondTeamMember],
        [this.thirdTeamMember, this.fourthTeamMember],
        [this.fifthTeamMember, this.sixthTeamMember]
    ];
}

,您的组件将如下所示

<h1>{{ title }}</h1>
<div class="team" *ngFor="let i of team">
    <span *ngFor="let j of i">
        {{j.name}}
        {{j.description}}
    </span>
</div>

如果你想使用功能, 数组不应该执行函数[this.firstTeamMember(), this.secondTeamMember()],将函数存储在数组中并在html中执行它

export class TeamComponent implements OnInit {
    public team: any[];
    title = ' Team ';

    constructor() {
        this.team = [
            [this.firstTeamMember, this.secondTeamMember],
            [this.thirdTeamMember, this.fourthTeamMember],
            [this.fifthTeamMember, this.sixthTeamMember]
        ];
    }
}

函数应该具有孤立变量而不是全局变量,因此从this.name更改为const name = 'name';

firstTeamMember(): {
    const name = 'Another name';
    const description = 'text';
}

secondTeamMember(): {
    const name = 'Another name';
    const description = 'text';
}

thirdTeamMember(): {
    const name = 'Another name';
    const description = 'text';
}

fourthTeamMember(): {
    const name = 'Another name';
    const description = 'text';
}

fifthTeamMember(): {
    const name = 'Another name.';
    const description = 'text';
}

sixthTeamMember(): {
    const name = 'Another name';
    const description = 'text';
}

Component.html

<h1>{{ title }}</h1>
<div class="team" *ngFor="let i of team">
    <span *ngFor="let j of i">
        {{j().name}}
    </span>
</div>

答案 1 :(得分:0)

我已经尝试过这种方式并且它有效,但它只显示我第六次成员六次

<h1>{{ title }}</h1>
 <div class="team" *ngFor="let i of team; let i = index">
  <span *ngFor="let j of i">
   {{j}}
  {{ name }}
  </span>
 </div>