Angular Input为什么未定义?

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

Why Angular Input is undefined?

问题

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

子组件:

  1. @Component({
  2. selector: 'app-test-grid',
  3. templateUrl: './test-grid.component.html',
  4. styleUrls: ['./test-grid.component.scss'],
  5. })
  6. export class TestGridComponent implements OnInit {
  7. @Input() memos: any[];
  8. constructor() {
  9. console.log(this.memos); // 打印undefined
  10. }
  11. ngOnInit() {
  12. console.log(this.memos); // 也打印undefined
  13. }
  14. }
  1. <div *ngIf="checker()">
  2. THIS IS DISPLAYED
  3. <app-test-grid>
  4. [memos]="test"
  5. </app-test-grid>
  6. </div>
  7. // parent component.ts
  8. test: number[] = [1, 2, 3, 4, 5, 6, 7];
  9. ngOnInit() {
  10. console.log(this.test); // 打印[1, 2, 3, 4, 5, 6, 7]
  11. }
  12. checker() {
  13. console.log('checker', this.test.length !== 0); // 这会打印true
  14. return this.test.length !== 0;
  15. }

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

英文:

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

Child Component:

  1. @Component({
  2. selector: &#39;app-test-grid&#39;,
  3. templateUrl: &#39;./test-grid.component.html&#39;,
  4. styleUrls: [&#39;./test-grid.component.scss&#39;],
  5. })
  6. export class TestGridComponent implements OnInit {
  7. @Input() memos: any[];
  8. constructor() {
  9. console.log(this.memos); // prints undefined
  10. }
  11. ngOnInit() {
  12. console.log(this.memos); // also prints undefined
  13. }
  14. }
  1. &lt;div *ngIf=&quot;checker()&quot;&gt;
  2. THIS IS DISPLAYED
  3. &lt;app-test-grid&gt;
  4. [memos]=&quot;test&quot;
  5. &lt;/app-test-grid&gt;
  6. &lt;/div&gt;
  7. // parent component.ts
  8. test: number[] = [1, 2, 3, 4, 5, 6, 7];
  9. ngOnInit() {
  10. console.log(this.test); // print [1,2,3,4,5,6,7]
  11. }
  12. checker() {
  13. console.log(&#39;checker&#39;, this.test.length !== 0); // this prints true
  14. return this.test.length !== 0;
  15. }

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赋值丢失,作为组件的内容。使用以下方式:

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

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

  1. &lt;app-test-grid [memos]=&quot;test&quot;&gt;
  2. &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:

确定