我正在尝试启动并运行我的第一个Angular应用,并且遇到一些错误。
我遇到了错误:
TS2304: Cannot find name 'result__i'
和TS2551: Property 'second__i' does not exist on type 'AppComponent'.
我希望输出:
result0:10
result1:14
但不起作用。
HTML代码:
<input type="number" [(ngModel)]="first">
<input type="number" [(ngModel)]="second_0">
<input type="number" [(ngModel)]="second_1">
<br>result0:{{result_0}}
<br>result1:{{result_1}}
<br><br>
<input type="submit" value="Submit" (click)="sum()">
app.component.ts:
export class AppComponent {
first = 6;
second_0 = 4;
second_1 = 8;
public sum() {
for (let _i = 0; _i < 2; _i++) {
result__i = this.first + this.second__i;
}
return false;
}
}
答案 0 :(得分:1)
模板:
<input type="number" [(ngModel)]="first">
<input type="number" [(ngModel)]="second[0]">
<input type="number" [(ngModel)]="second[1]">
<br>result0:{{result[0]}}
<br>result1:{{result[1]}}
<br><br>
<input type="submit" value="Submit" (click)="sum()">
在组件中:
first = 6;
second = [4, 8];
result = []
public sum() {
for (let _i = 0; _i < 2; _i++) {
this.result[_i] = this.first + this.second[_i];
}
}
答案 1 :(得分:0)
在您的组件中进行设置。
export class AppComponent {
first = 6;
second_0 = 4;
second_1 = 8;
public sum() {
let result__i = 0
let second__i = 0
for (let _i = 0; _i < 2; _i++) {
return result__i = this.first + second__i;
}
}
}
编译器抱怨此类属性result__i
和second__i
未定义
答案 2 :(得分:0)
我会以一种动态的方式做这样的事情,因此如果secondNos
列表中的项目增加,则无需更改HTML代码
改良的HTML代码:
<input type="number" [(ngModel)]="first">
<span *ngFor="let obj of secondNos">
<input type="number" [(ngModel)]="obj">
</span>
<span *ngFor="let obj of result; let i=index">
<br>result {{i}} : {{obj}}
</span>
<br>
<br>
<input type="submit" value="Submit" (click)="sum()">
在TS中:
export class AppComponent {
first = 6;
secondNos = [4, 8, 123]; // Incase of new items in the list no need to change in HTML Code
result = [];
public sum() {
this.secondNos.forEach(x => {
var addition = this.first + x;
this.result.push(addition)
})
}
}