Angular 中按钮的 Undefined Input()

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

Undefined Input() from Button in Angular

问题

你的输入逻辑看起来是正确的。在你的代码中,你使用了@Input()来接收父组件传递的id,然后在子组件的ngOnInit方法中打印了它。

在这里,你无需将父组件的id传递给app.component.ts,因为它已经通过属性绑定传递给了子组件。你可以直接在子组件中使用this.getId来访问父组件传递的id。

如果你在控制台中打印this.getId并且没有看到预期的值,可以检查一下父组件中的setId方法是否正确设置了id的值。另外,确保你的数据流正常,即父组件的list包含正确的数据。

总的来说,根据你的代码片段,输入逻辑看起来没有问题,但问题可能在其他地方。确保你的数据流和模板绑定都正确设置。

英文:

I have a component within the directory of another component and am trying to get the parent's id value to the child. However, I seem to be unable to get the "string" that I will convert to a number within the child component. Since I am still learning I tried to implement it with examples but had no luck.

Parent Component TS

import { Component, EventEmitter, Output } from '@angular/core';
import { ApiserviceService } from '../service/service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  id : any;
  list : any;
  
  constructor(private _apiservice: ApiserviceService, private router: Router) {} //For rest of code

  setId(idHTML: number) {
    console.log(idHTML); // Works, Typeof returns number
    this.id = idHtml.toString(); // Change to String
    this.router.navigate(['/child']);
  }
}

Parent HTML

<body>
  <div class="outer-container">
    <div *ngFor="let index of list">
      <div class="image-container">
        <img class="background" src="{{index.poster_path}}">
        <img class="poster" src="{{index.poster_path}}">
        <p class="title">{{index.title}}</p>
        <p class="context">{{index.overview}}</p>
        <button class="button" type="submit" 
          (click)="setId(index.id)">
          Details
        </button>  
      </div>
    </div>
  </div>
</body>
<app-child [getId]="id"></app-child>

Child Component TS

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Input() getId: any;

  constructor() {}

  ngOnInit() {
    console.log(this.getId);
  }
}

Is my logic of Input wrong? Do I need to send parent's id to the app.component.ts first and then retrieve it back to the child component in getId?

答案1

得分: 1

当子组件初始化时,getId 属性未定义。因此,当您在 ngOnInit 上调用它时,它会引发错误。

您可以将它移到 ngOnChanges() 中。

示例

# 在导入中添加 SimpleChanges
import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';

ngOnChanges(changes: SimpleChanges) {
    if (changes.getId) {
        console.log(this.getId);
    }
}

请注意,上述内容仅为代码部分的翻译。

英文:

At the time the child component is initialized getId property is not defined. So when you call this on ngOnInit it will throw an error.

What you can do is you can move it to ngOnChanges().

Example

# Add SimpleChanges to the import
import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';


ngOnChanges(changes: SimpleChanges) {
    if(changes.getId) {
        console.log(this.getId);
    }
}

答案2

得分: 0

我不确定你是否可以将组件用作子组件,然后希望导航到它,这似乎没有意义。

你是否尝试了以下之一:

  1. 在列表中,当你点击一个项目时,你获取该项目的ID并转到其详细信息或在某个地方显示其详细信息?你可以通过HTML路由传递ID,像这样:

<button (click)="viewCustomer(orderData?.customer?.id)" class="btn btn-xs" type="button">
viewCustomer(id){
this.location.navigateByUrl('/app/customers/view/' + id);
}

或者你可以像这样传递它:

<a class="btn btn-white-view" [routerLink]="['/app/customers/view/',orderData?.customer?.id]">view

在你的其他组件中,你可以通过activated route访问传递的ID:

this.route.paramMap.subscribe((params) => {
this.currentId = params.get('id');
});

根据我认为的问题,这应该对你有用,如果不行,请在评论中告诉我们,我们会找出解决方法。

另一种方法是在定义路由的路由文件中传递数据,
或者
你可以在窗口历史状态属性中设置数据并检索它,虽然方法是相同的,但在这里你可以发送更多的东西而不仅仅是一个ID。

navigateWithState() {
this.router.navigateByUrl('/123', { state: { hello: 'world' } });
}

<a routerLink="/details" [state]="{ hello: 'world' }">Go
使用以下方式获取它:

this.state$ = this.activatedRoute.paramMap
.pipe(map(() => window.history.state))

  1. 如果你只想将数据传递给你组件内的一个组件,比如一个模型或者屏幕上的某个地方,不要使用导航,只需使用输入,你将得到数据,就像你在示例中所做的那样,只需排除整个导航部分。

如果以上方法都不起作用,或者你无法理解某些内容,我们可以讨论并一起解决。

英文:

I don't know for sure that you can use a component as a child and then want to navigate to it just doesn't makes sense.

are you trying one of these:

  1. in a list when you click on an item you get that item id and go to its details or show its details in something? what you can do is, pass the id using route in htlm.

    <button (click)="viewCustomer(orderData?.customer?.id)" class="btn btn-xs" type="button"><i
    class="simple-icon-eye" style="font-size: 15px;"></i></button>
    viewCustomer(id){
    this.location.navigateByUrl('/app/customers/view/' + id);
    }

or you can pass it like

&lt;a class=&quot;btn btn-white-view&quot; [routerLink]=&quot;[&#39;/app/customers/view/&#39;,orderData?.customer?.id]&quot;&gt;view&lt;/a&gt;

in your other component you can access the passed id via activated route

this.route.paramMap.subscribe((params) =&gt; {
    this.currentId = params.get(&#39;id&#39;);
  });

For what I think your problem is this should work for you if not, come in the comments and we will figure it out.

Another way to do this is to pass data in the router file where you are defining the routes,
OR
you can set you data in a windows history state property and retrieve it, although the method is identical but here you can send more then just an id.

navigateWithState() {
this.router.navigateByUrl(&#39;/123&#39;, { state: { hello: &#39;world&#39; } });

}
OR
<a routerLink="/details" [state]="{ hello: 'world' }">Go</a>
get it using

this.state$ = this.activatedRoute.paramMap
  .pipe(map(() =&gt; window.history.state))
  1. if you just want to pass data to a component that is inside your component. like a model or a component below or somewhere on the screen don't use navigation just use input and you will get the data as you have done in your example jus exclude the whole navigation stuff.

If none work or you can't understand something, we can discuss and work through it.

huangapple
  • 本文由 发表于 2023年5月15日 13:18:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251044.html
匿名

发表评论

匿名网友

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

确定