【问题标题】:Typescript Angular variable empty in componentTypescript Angular变量在组件中为空
【发布时间】:2020-07-03 04:40:57
【问题描述】:

我有一个网页,其中循环调用一个组件 10 次。我将数据传递给我的组件并且它可以工作。但这是我的问题。 在我的组件中,我想打印对象值,但它始终为空。

在我的组件 HTML 中:

<div>
   Name: {{ teamInfo.name }}
</div>
<div>
   <mat-table [dataSource]="List" class="mat-elevation-z8">
      <ng-container matColumnDef="ronde">
        <mat-header-cell *matHeaderCellDef matTooltip="Ronde">rd</mat-header-cell>
        <mat-cell *matCellDef="let element">{{ element.ronde }}</mat-cell>
        <mat-footer-cell *matFooterCellDef> </mat-footer-cell>
      </ng-container>
   </mat-table>
</div>

mat-table 一切正常,因为这些数据是在 Init 代码中接收的。

为了让代码更清晰,我直接不访问数据库。

.ts 文件:

export class MyComponent implements OnInit {
  teamInfo:  TeamObject;

  @Input() List: DraftList;

  constructor() {}

  ngOnInit() {
    console.log("DraftList", this.List);
    this.getConcessionInfo();
  }

  public getConcessionInfo() { 
    this.teamInfo.name ="TeamName";
    console.log(this.teamInfo.name);
  }

}

问题是:我的代码在 .ts 代码中正常工作(控制台日志有数据,例如:console.log(this.teamInfo.name);)

但是在 HTML 组件中,这一行是空的: Name: {{ teamInfo.name }}

@Input 中接收的数据在 HTML 中正确打印。 我是这个编程之王的新手。有人可以看到为什么我的变量不在 HTML 中打印吗?

谢谢

【问题讨论】:

  • 为什么getConcessionInfo 是一个异步函数?
  • 对不起,我尝试一下。我将删除异步。发帖的时候忘记删了

标签: angular typescript components


【解决方案1】:

//第二种解决方案

teamInfo = new TeamObject();

ngOnInit() {
  this.getConcessionInfo();
}

public async getConcessionInfo() {
  this.teamInfo.name = "TeamName";
  console.log(this.teamInfo.name);
}

【讨论】:

  • 我的问题是关于 HTML 中的 PRINT 值。你的代码给了我同样的东西。我想知道为什么 HTML 不打印值?你测试你的结果了吗?谢谢
  • 是的,我已经尝试过了,它也会渲染到浏览器中,参见示例
  • 两种解决方案都可以尝试
【解决方案2】:

希望它会起作用,谢谢。

  teamInfo: TeamObject;

  ngOnInit() {
    this.getConcessionInfo();
  }

  public async getConcessionInfo() {
    this.teamInfo = Object.assign(new TeamObject, this.teamInfo);
    this.teamInfo.name = "TeamName";
    console.log(this.teamInfo.name);
  }

first solution

【讨论】:

  • 我的问题是关于 HTML 中的 PRINT 值。你的代码给了我同样的东西。我想知道为什么 HTML 不打印值?你测试你的结果了吗?谢谢
猜你喜欢
  • 2023-04-09
  • 2017-10-11
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2018-04-10
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多