首页 > 解决方案 > 如何使用 Visual Studio 中的默认 Angular 项目导入组件

问题描述

我在使用默认角度视觉工作室项目时遇到角度问题。我目前不确定如何将多个组件添加到 .ts 文件中,我开始非常简单

我要做的就是将现有的“计数器”组件添加到现有的 fetch-data.html 页面

import { Component } from '@angular/core';

@Component({
  selector: 'app-counter-component',
  templateUrl: './counter.component.html'
})

export class CounterComponent {
    public currentCount = 0;

    public incrementCounter() {
      this.currentCount++;
    }
}

获取数据组件.html

<h1 id="tableLabel">Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>
<h1>Counter</h1>

<p>This is a simple example of an Angular component.</p>

<p aria-live="polite">Current count: <strong>{{ counter }}</strong></p>

<button class="btn btn-primary" (click)="counter.incrementCounter()">Increment</button>

<p *ngIf="!forecasts"><em>Loading...</em></p>

<table class='table table-striped' aria-labelledby="tableLabel" *ngIf="forecasts">
  <thead>
    <tr>
      <th>Date</th>
      <th>Temp. (C)</th>
      <th>Temp. (F)</th>
      <th>Summary</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let forecast of forecasts">
      <td>{{ forecast.date }}</td>
      <td>{{ forecast.temperatureC }}</td>
      <td>{{ forecast.temperatureF }}</td>
      <td>{{ forecast.summary }}</td>
    </tr>
  </tbody>
</table>
import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CounterComponent } from '../counter/counter.component';

@Component({
    selector: 'app-fetch-data',
    templateUrl: './fetch-data.component.html',
})

export class FetchDataComponent
{
  public counter: CounterComponent;
  public forecasts: WeatherForecast[];

    constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string)
    {
      http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result =>
      {
          this.forecasts = result;
      }, error => console.error(error));
  }
}

interface WeatherForecast {
  date: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

如您所见,我已导入 CounterComponent 并将其添加到导出类

export class FetchDataComponent
{
  public counter: CounterComponent;

但我得到的只是错误。“incrementCounter 不是函数”我不确定导入 CounterComponent 后该去哪里

如何将计数器组件导入并添加到 fetch-data.html 页面?导入和使用此组件的正确方法是什么

标签: angulartypescriptvisual-studiodebuggingangular-components

解决方案


  1. 确保两个组件都在模块声明数组中。
  2. 您的 FetchDataComponent 将是一个父组件, CounterComponent 将是它的子组件,这意味着它将位于父模板内,这样它们就可以相互交互并共享数据。
  3. CounterComponent 有一个选择器应用程序计数器组件。像这样将它放在 FetchDataComponent 模板中<app-counter-component></app-counter-component>

获取数据.component.html

<h1> Some heading</h1>
<app-counter-component></app-counter-component>
<h2> The End </h2>


推荐阅读