我正在尝试访问元素,但它显示错误
属性“元素”没有初始值设定项
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-server-element',
templateUrl: './server-element.component.html',
styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit {
@Input('srvElement') element: {type: string, name: string, content: string}; <--- This doesn't work
constructor() { }
ngOnInit() { }
}
为
element
输入提供一些默认值,或者如果您确定会提供该值,则在此 @Input('srvElement') element!: {type: string, name: string, content: string};
后面放置 感叹号。我不建议设置
"strictPropertyInitialization": false
,因为当我们不希望它们被初始化时,看到未初始化的值非常有用。它可以避免您将来出现运行时问题。
您需要初始化输入值并确保提供它
@Input({ required: true, alias: 'srvElement' }) element!: Type; // For required inputs in pre-signal Angular versions
srvElement = input.required<Type>(); // using required input with signals
或者通过提供元素的默认值。
@Input({ required: true, alias: 'srvElement' }) element: Type = {type: 'type', name: 'default name', content: 'default content'};
当您不想使用所需的输入并且希望不定义该值时,您应该处理未定义的值并在输入中使用
?
,例如:
@Input('srvElement') element?: {type: string, name: string, content: string}; // when your component can be used without providing this input at all
或
@Input('srvElement') element: {type: string, name: string, content: string} | undefined; // when your component input is required but it's value can be undefined