首页 > 解决方案 > 如何让子数据绑定采用字符串而不是父主机属性?

问题描述

使用 Angular 9,我为什么会得到:

 src/app/today-chart/today-chart.component.html:3:50 - error TS2339: Property 'large' does not exist on type 'TodayChartComponent'.

3     <line-chart [curveData]="chart" [graphSize]="large"></line-chart>

为什么它期望large成为今天图表组件的主机属性?如何使折线图的目标属性[graphSize]接受large为字符串而不是父级的绑定主机属性?

今天-chart.component.html:

<div class="chart-body">
  <div *ngFor="let chart of charts | async | daysFilter:1">
    <line-chart [curveData]="chart" [graphSize]="large"></line-chart>
  </div>
<div>

今天-chart.component.ts

import { Component, OnInit} from '@angular/core';
import { GetChartDataService } from '../get-chart-data.service';

@Component({
  selector: 'app-today-chart',
  templateUrl: './today-chart.component.html',
  styleUrls: ['./today-chart.component.css']
})

export class TodayChartComponent implements OnInit {
  public charts;

  constructor(
    private getChartDataService: GetChartDataService,
    private graphSizeValue: String,
  ) {}

  ngOnInit() {
    this.charts = this.getChartDataService.getData();
  }

}

折线图.component.ts:

import { Component, Input, ViewChild, ElementRef } from '@angular/core';
import { LineChartService } from './line-chart.service';

@Component({
  selector: 'line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})

export class LineChartComponent {
  @Input() curveData: Array<object>;
  @Input()
  get graphSize() {
    return this.graphSizeValue;
  }


  constructor(
    private lineChartService: LineChartService,
    private elRef: ElementRef,
    private graphSizeValue: String,
  ) { }

  ngAfterViewInit() {
    this.lineChartService.makeGraph(this.curveData, this.elRef.nativeElement);
  }
}

标签: angular

解决方案


您正在尝试将不存在的变量传递给没有意义的 Input。我想你想传递一个字符串,这意味着你有 2 个选择:

<line-chart [curveData]="chart" [graphSize]="'large'"></line-chart>

或者

<line-chart [curveData]="chart" graphSize="large"></line-chart>

使用括号,除非您添加单引号,否则 angular 将在您的 ts 文件中搜索变量。没有括号, large 将被视为字符串


推荐阅读