我正在学习 Angular 6,而且对它还很陌生。
我的目标是定义一个类函数,然后从连接的组件中调用它,但出现以下错误。
TypeError: _co.installation.selectOrDeselect is not a function
安装.ts
export class Installation {
id: number;
name: string;
img: string;
version: number;
agents: number;
ip: string;
connection: string;
selection: string;
selectOrDeselect() {
if (this.selection == 'not-selected') {
this.selection = 'selected';
} else {
this.selection = 'not-selected';
}
}
}
installations.component.ts
import { Component, OnInit } from '@angular/core';
import { Installation } from '../installation';
@Component({
selector: 'app-installations',
templateUrl: './installations.component.html',
styleUrls: ['./installations.component.css'],
})
export class InstallationsComponent implements OnInit {
installation: Installation = {
id: 1,
name: 'Master',
img: 'assets/logo.jpg',
version: 7,
agents: 95,
ip: '192.168.0.1',
connection: 'not-connected',
selection: 'not-selected'
};
constructor() { }
ngOnInit() {
}
}
installations.component.html
<div class=""class="col-2 installationContainer {{installation.selection}} {{ installation.connection }}" (click)="installation.selectOrDeselect()">
<h3>{{ installation.name }}</h3>
<img src="{{ installation.img }}">
<div><label>versione: </label>{{ installation.version }}</div>
<div><label>agenti: </label>{{ installation.agents }}</div>
<div><label>ip: </label>{{ installation.ip }}</div>
</div>
最佳答案
安装:安装= {...}
这里您只是指定对象类型以供 typescript 编译器进行编译时类型检查。 Installation
类型不会在运行时被获取。只是你的对象。你需要做的是:
installation = new Installation();
让方法可用。
您可能还需要为 Installation
类定义一个构造函数,该构造函数接受所有属性并进行设置。
export class Installation {
constructor(
public id: number;
public name: string;
public img: string;
public version: number;
public agents: number;
public ip: string;
public connection: string;
public selection: string;
){}
selectOrDeselect() {
if (this.selection == 'not-selected') {
this.selection = 'selected';
} else {
this.selection = 'not-selected';
}
}
}
和初始化:
installation = new Installation(1,'Master','assets/logo.jpg',7,95,'192.168.0.1','not-connected','not-selected');
关于angular - TypeError : _co. class.function 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50347565/