angular - 如何使用 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 页面?导入和使用此组件的正确方法是什么
解决方案
- 确保两个组件都在模块声明数组中。
- 您的 FetchDataComponent 将是一个父组件, CounterComponent 将是它的子组件,这意味着它将位于父模板内,这样它们就可以相互交互并共享数据。
- CounterComponent 有一个选择器应用程序计数器组件。像这样将它放在 FetchDataComponent 模板中
<app-counter-component></app-counter-component>
获取数据.component.html
<h1> Some heading</h1>
<app-counter-component></app-counter-component>
<h2> The End </h2>
推荐阅读
- 3d - PDDL:如何从 2D 传递到 3D
- javascript - JavaScript - 多个输入文件,onchange 总是影响第一个
- mysql - 在 Mysql 中触发执行时更新数据?
- django - 为什么我们使用序列化程序而不是完全清理来验证模型,或者我们应该互换使用它们?
- java - 同步并行 API 请求以从长时间运行的查询中返回相同结果而无需多次执行的最佳实践是什么?
- ruby - 如何在 ruby 中使用 ca_file 正确使用 Net::HTTP 自签名证书?
- flutter - 在 Flutter 中发布的“flutter build apk”出现错误
- python - 如何修复统计模型(模型缺少所需的结果变量)
- paypal - 如何修复 GetPaymentOptions API 的“520002 内部错误”响应?
- node.js - Microsoft Bot Framework - 不推荐使用 Bot State API。有关如何替换的详细信息,请参阅 https://aka.ms/I6swrh