如何使用Angular 7从另一个组件访问组件值

时间:2019-01-27 12:35:27

标签: angular

我使用此代码从组件StripeComponent到CreditCardComponent访问“地址”值。我得到的是空值,而不是StripeComponent中的实际值

这是我在CreditCardComponent中的子代码:

import { StripeComponent} from '../stripe/stripe.component';

@Component({
  providers: [StripeComponent],
  selector: 'app-creditcard',
  templateUrl: './creditcard.component.html',
  styleUrls: ['./creditcard.component.css']
})
export class CreditCardComponent implements OnInit {

  @Input() address : Address;
  @Input('address') ccAddress: Address;

  constructor(private creditCardService: CreditCardService,

  public stripeScriptTag: StripeScriptTag) {
    this.stripeScriptTag.setPublishableKey( this.publishableKey )
    this.ccAddress = this.creditCardComponent.ccAddress;
    console.log('this is the ccAddress', this.ccAddress);
}

这是StripeComponent中的父代码

public address =
new Address(
  {
    name:"",
    address_city: "",
    address_line1: "",
    address_line2: "",
    address_state: "",
    address_zip: "",
    address_country: ""
  }
)

这是Stripecomponent.html代码,creditcardcomponent.html没有html

<div class = form>
  <form (ngSubmit)="onSubmitAddress()"  class="address" >

    <mat-form-field class="name-width-height">
      <input matInput name="name" 
       type="text" required [(ngModel)]="address.name"
     >
     <mat-placeholder class="placeholder">Name</mat-placeholder>
    </mat-form-field>


       <button type="submit" mat-raised-button color="primary"class="btn 
     address_form">Submit</button>
  </form>
</div>

2 个答案:

答案 0 :(得分:3)

@Input 数据将在 ngOnInit

中可用,而不是使用ngOninit生命周期访问构造函数。
export class CreditCardComponent implements OnInit {

    ngOnInit(){
        this.ccAddress = this.creditCardComponent.ccAddress;
        console.log('this is the ccAddress', this.ccAddress);
    }

答案 1 :(得分:1)

组件不用作输入,您只需将变量传递给子组件,因此父模板应类似于:

<app-creditcard [ccAddress]="address"></app-creditcard>

在子组件中,根据需要将其标记为输入。就像OnInit(或OnChanges)中提到的Sajeetharan。

还要从子组件中删除providers: [StripeComponent]

以下是示例:DEMO