我正在尝试将 ts 变量绑定(bind)到 html 文件,我尝试了很多方法但我不能。也许我在 ts 文件中设置的值错误。这是模板代码:
<div class="md-dialog-container">
<h2>{{message}}</h2>
<button type="submit" class="button-style btn btn-info" (click)="closeDialog()">Close</button>
</div>
这是该模板的 ts 文件:
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-error-dialog',
templateUrl: './error-dialog.component.html',
styleUrls: ['./error-dialog.component.css']
})
export class ErrorDialogComponent implements OnInit {
message: string;
constructor(private dialogRef:MatDialogRef<ErrorDialogComponent>, @Inject(MAT_DIALOG_DATA) data) {
this.message = data;
}
ngOnInit(): void {
}
closeDialog() {
this.dialogRef.close();
console.log(this.message);
}
}
如您所见,我正在获取消息值作为参数。当我关闭对话框时将其打印到控制台时,它打印正确,但我无法在模板页面中显示它。我该如何解决这个问题? 我也尝试过 this.message 而不仅仅是 html 中的message,但它也不起作用。
最佳答案
根据您的控制台日志,message
处的值不是字符串,而是位于如下形状的对象上:
{ string: "My String" }
因此,当使用 toString()
将其转换为 string
时,您将获得 [Object object]
作为输出。因此,在分配 this.message = data
的地方,您实际上应该执行 this.message = data.string
:
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-error-dialog',
templateUrl: './error-dialog.component.html',
styleUrls: ['./error-dialog.component.css']
})
export class ErrorDialogComponent implements OnInit {
message: string;
constructor(private dialogRef:MatDialogRef<ErrorDialogComponent>, @Inject(MAT_DIALOG_DATA) data) {
// Change made below, so your variable is of type string, not any
this.message = data.string;
}
ngOnInit(): void {
}
closeDialog() {
this.dialogRef.close();
console.log(this.message);
}
}
否则,在您的模板中,您也可以执行 {{message.string}}
:
<div class="md-dialog-container">
<!-- Change made to read the value in the object, not the object itself -->
<h2>{{message.string}}</h2>
<button type="submit" class="button-style btn btn-info" (click)="closeDialog()">Close</button>
</div>
如果您希望使用新对象更新 message
对象并保持所有内容同步,这很有用。
关于javascript - 如何将ts变量绑定(bind)到html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63160516/