dis*_*ame 3 intellij-idea typescript angular
我有一个简单的注册组件,它除了将表单提交到涅槃之外什么也不做。然而,IntelliJ 认为这onSubmit可能是static。如果我将签名更改为,static我无法调用该方法 - 至少据我所知 - 所有答案都表明无法从模板内调用静态组件方法。
显然 IntelliJ 没有意识到我实际上是在模板中调用这个方法,因此错误地建议创建该方法static。
有没有解决方法,或者我只能忍受这个警告?
这是一个例子:
成分:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
data: any;
constructor() {
this.data = {
username: ''
};
}
// WARNING: Method can be static
onSubmit(event) {
alert('Submitting ..');
}
ngOnInit() {
}
}
Run Code Online (Sandbox Code Playgroud)
模板:
<form (ngSubmit)="onSubmit($event)">
<mat-grid-list cols=1>
<mat-form-field>
<input matInput placeholder="Username" [(ngModel)]="data.username" name="uname">
</mat-form-field>
<mat-grid-list cols=2>
<button mat-button type="submit">Ok</button>
<button mat-button>Cancel</button>
</mat-grid-list>
</mat-grid-list>
</form>
Run Code Online (Sandbox Code Playgroud)
Intellij 建议将此类方法设为静态,因为它们不会触及实例的任何状态。
您可以将 onSubmit 方法设为静态:
static onSubmit(event) {
alert('Submitting ..');
}
Run Code Online (Sandbox Code Playgroud)
然后 intellij 会警告您将此方法放在类的非静态方法之前。
然后,您需要在组件中提供一个 getter,以便像您一样从模板中调用静态成员。
onSubmit = RegisterComponent.onSubmit;
Run Code Online (Sandbox Code Playgroud)
所以,你的代码应该是:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
data: any;
onSubmit = RegisterComponent.onSubmit;
static onSubmit(event) {
alert('Submitting ..');
}
constructor() {
this.data = {
username: ''
};
}
ngOnInit() {
}
}
Run Code Online (Sandbox Code Playgroud)
这将会起作用,并且您不会收到任何警告。
| 归档时间: |
|
| 查看次数: |
1765 次 |
| 最近记录: |