【发布时间】:2021-04-23 03:37:43
【问题描述】:
我有这个问题,我用路由制作了三个不同的组件。问题是当我打开我的不同组件时,它们会在我打开它们的那一刻循环两次。这是什么原因造成的,我该如何摆脱它?
这是一个示例组件,console.log 在我打开它时会运行两次。
import { Component, OnInit } from '@angular/core';
import nameData from '../../names/names.json'
interface INames {
name: string,
amount: number
}
const { names } = nameData
@Component({
selector: 'app-four',
templateUrl: './four.html',
styleUrls: ["./four.css"]
})
export class FourComponent {
nameArray: Array<INames> = names
constructor() {
}
hasName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa")
return this.nameArray.some(elem => elem.name === nameParam)
}
}
这里是 app.module.ts 和 app-routing.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OneComponent } from './requirements/one/one';
import { TwoComponent } from './requirements/two/two';
import { ThreeComponent } from './requirements/three/three';
import { FourComponent } from './requirements/four/four';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HeaderComponent } from './header/header';
@NgModule({
declarations: [
AppComponent,
OneComponent,
TwoComponent,
ThreeComponent,
FourComponent,
HeaderComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing-module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home';
import { FourComponent } from './requirements/four/four';
import { OneComponent } from './requirements/one/one';
import { ThreeComponent } from './requirements/three/three';
import { TwoComponent } from './requirements/two/two';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'one', component: OneComponent },
{ path: 'two', component: TwoComponent },
{ path: 'three', component: ThreeComponent },
{ path: 'four', component: FourComponent }
]
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我真的很困惑,为什么我一按下组件按钮它就会循环功能?
【问题讨论】:
-
你在哪里使用 hasName() 函数。可以分享一下吗?
-
如果您在模板中使用
hasName,那是因为它会多次渲染。只有在必要时才应谨慎调用此类操作 - 当您更改输入值时。
标签: html angular typescript