[英]how to pass variable from one function to another function in same component.ts in angular 6
[英]Regarding Angular 2 - Extract a Variable from An Array (related to front side: html and component.ts)
这是我的代码。 我有一个名为“ mydmcanotice”的数组,它具有四个属性,如{{}}括号中所示。 对于mydmcanotice中的每个dmca,我都有一个按钮。 当我单击一个按钮时,我希望dmca.nameofsong显示在我的文本区域中,但是我不确定如何执行此操作。
例如,mydmcanotice数组中的第一个元素,其nameofsong属性称为“ Victor”。 因此,当我单击按钮(发送DMCA通知)时,我希望名称victor出现在文本区域中。 另外,当我单击按钮时,showbody布尔值变为true(sendNotice()使它在单击时变为true)。
我是Angular 2的新手,如果这很简单,请原谅我。 如果需要,我可以添加component.ts文件的代码。 谢谢!
<ul>
<li *ngFor = "let dmca of mydmcanotice">
{{dmca.nameofsong}} - {{dmca.nameofsonguploader}} - {{dmca.nameofpersonsending}} - {{dmca.content}}
<br><button (click)="sendNotice()" >Send DMCA Notice!</button>
</li>
</ul><br>
<div *ngIf = "showbody == true">
<textarea rows = "15" cols = "150" [(ngModel)] = "content">
</textarea>
</div>
您需要确保将变量传递到sendNotice()
,该变量指向数组中的相应歌曲,否则发送通知将不知道您要用文本填充什么数据。
使用数组上的indexOf()
将数组的索引添加到sendNotice()
:
<button (click)="sendNotice(mydmcanotice.indexOf(dmca))" >Send DMCA Notice!</button>
一旦将索引传递给sendNotice()
,您就可以使用该索引来访问您的数组:
sendNotice(index) {
this.somebody = true;
this.content = this.mydmcanotice[index].nameofsong;
}
这是该组件的工作版本的示例:
import { Component } from '@angular/core';
@Component({
selector: 'dmca-app',
template: `
<ul>
<li *ngFor = "let dmca of mydmcanotice">
{{dmca.nameofsong}} - {{dmca.nameofsonguploader}} - {{dmca.nameofpersonsending}} - {{dmca.content}}
<br><button (click)="sendNotice(mydmcanotice.indexOf(dmca))" >Send DMCA Notice!</button>
</li>
</ul><br>
<div *ngIf="somebody">
<textarea rows = "15" cols = "150" [(ngModel)]="content">
</textarea>
</div>`
})
export class DMCAComponent {
// Mock Data
mydmcanotice = [
{
nameofsong: "Heathens",
nameofsonguploader: "Twenty One Pilots",
nameofpersonsending: "Tyler",
content: "I am content",
},
{
nameofsong: "Style",
nameofsonguploader: "Taylor Swift",
nameofpersonsending: "Taylor",
content: "I am also Content",
}
];
// Variables
content = { };
somebody = false;
// Constructor
constructor() { }
// Functions
sendNotice(index) {
this.somebody = true;
this.content = this.mydmcanotice[index].nameofsong;
}
}
此外,这是ngModel和indexOf的一些链接:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf https://angular.io/docs/ts/latest/api/forms/index/NgModel-directive .html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.