为什么要传递元素:{ type: string, name: string, content: string };不起作用?

问题描述 投票:0回答:2

我正在尝试访问元素,但它显示错误

属性“元素”没有初始值设定项

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() { }

}
angular typescript
2个回答
2
投票

element
输入提供一些默认值,或者如果您确定会提供该值,则在此 @Input('srvElement') element!: {type: string, name: string, content: string}; 后面放置
感叹号
。我不建议设置
"strictPropertyInitialization": false
,因为当我们不希望它们被初始化时,看到未初始化的值非常有用。它可以避免您将来出现运行时问题。


0
投票

您需要初始化输入值并确保提供它

@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
© www.soinside.com 2019 - 2024. All rights reserved.