Angular Input为什么未定义?

huangapple go评论63阅读模式
英文:

Why Angular Input is undefined?

问题

我有一个典型的简单情况,但在这种情况下,@Input() 不起作用...

子组件:

@Component({
  selector: 'app-test-grid',
  templateUrl: './test-grid.component.html',
  styleUrls: ['./test-grid.component.scss'],
})
export class TestGridComponent implements OnInit {
  @Input() memos: any[];

  constructor() {
    console.log(this.memos); // 打印undefined
  }

  ngOnInit() {
    console.log(this.memos); // 也打印undefined
  }
}
<div *ngIf="checker()">
  THIS IS DISPLAYED
  <app-test-grid>
    [memos]="test"
  </app-test-grid>
</div>

// parent component.ts
test: number[] = [1, 2, 3, 4, 5, 6, 7];

ngOnInit() {
  console.log(this.test); // 打印[1, 2, 3, 4, 5, 6, 7]
}

checker() {
  console.log('checker', this.test.length !== 0); // 这会打印true

  return this.test.length !== 0;
}

这段代码有什么问题?这是非常基础的情况...我尝试找了一些相关的帖子,但没有找到答案。

英文:

I have typical easy situation but in that case @Input() does not working...

Child Component:

@Component({
  selector: &#39;app-test-grid&#39;,
  templateUrl: &#39;./test-grid.component.html&#39;,
  styleUrls: [&#39;./test-grid.component.scss&#39;],
})
export class TestGridComponent implements OnInit {
  @Input() memos: any[];

  constructor() {
    console.log(this.memos); // prints undefined
  }

  ngOnInit() {
    console.log(this.memos); // also prints undefined
  }
}
&lt;div *ngIf=&quot;checker()&quot;&gt;
  THIS IS DISPLAYED
  &lt;app-test-grid&gt;
    [memos]=&quot;test&quot;
  &lt;/app-test-grid&gt;
&lt;/div&gt;

// parent component.ts
  test: number[] = [1, 2, 3, 4, 5, 6, 7];

  ngOnInit() {
    console.log(this.test); // print [1,2,3,4,5,6,7]
  }

 checker() {
    console.log(&#39;checker&#39;, this.test.length !== 0); // this prints true

    return this.test.length !== 0;
  }

what's wrong with this code? this is very rudimentary case... I tried to found some another posts related but I didn't found answer.

答案1

得分: 2

你关闭了app-test-grid标签,因此memos赋值丢失,作为组件的内容。使用以下方式:

<app-test-grid [memos]="test">
</app-test-grid>
英文:

You closed the app-test-grid tag so the memos assignment is lost as the content of the component. Use this:

&lt;app-test-grid [memos]=&quot;test&quot;&gt;
&lt;/app-test-grid&gt;

huangapple
  • 本文由 发表于 2023年2月7日 02:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定