【发布时间】:2020-07-24 04:17:30
【问题描述】:
我有一个数据模型类,比如说:
class Question {
body: string;
get bodyForTableRow(): string {
return this.body.replace("\n", " // ");
}
}
在组件 html 模板中,我使用以下声明来评估 getter 值:
{{ oneQuestion.bodyForTableRow }}
但不是 value,而是用 // 符号替换新行,我得到一个空字符串。
当我使用时
{{ oneQuestion.body }}
它显示正文内容。
为什么会这样?我是否应该始终使用 real 字段将它们映射到 html-components 和 getter 不适合这种情况?
更新
当模板中的声明看起来像这样时
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- other columns skipped -->
<ng-container matColumnDef="body">
<th mat-header-cell *matHeaderCellDef>Question Body</th>
<td mat-cell *matCellDef="let oneQuestion">
{{ oneQuestion.body }}
</td>
</ng-container>
</table>
它在每个表格行中显示body 内容。但是当我使用这段代码时:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- other columns skipped -->
<ng-container matColumnDef="body">
<th mat-header-cell *matHeaderCellDef>Question Body</th>
<td mat-cell *matCellDef="let oneQuestion">
{{ oneQuestion.bodyForTableRow }}
</td>
</ng-container>
</table>
它显示空行。
更新 2
这样声明的问题数据模型类:
export class QuestionDataModel {
body: string; // public access field for template
constructor(bodyValue: string) {
this.body = bodyValue;
}
}
数据源是这样声明的:
dataSource: QuestionDataModel[];
我通过 rest-call 填充数据源
const url: string = `/questions/all`;
this.http.get(url).subscribe(
(data: QuestionDataModel[]) => {
this.dataSource = data;
},
(error) => this.reportServerError(error)
);
【问题讨论】:
-
您实际上是在创建
Question类的实例吗?仅使用类型断言不会创建Question的实例,并且您将无法访问getter/setters/其他方法。 -
@cjd82187 我已经发布了我的问题的更新。它澄清了吗?
-
@Rafael 不,更新没有说明,在这种情况下,我们需要看看您是如何获取和创建
dataSource的。似乎那里正在发生可疑的事情。 -
@bryan60 我会尽快更新我的问题。谢谢。
-
@bryan60 我又更新了我的问题。
标签: angular typescript