簡體   English   中英

將數據傳遞到Angular1應用程序中的降級Angular2組件

[英]Passing data into a downgraded Angular2 component within an Angular1 Application

我對Angular很新,所以如果這是一個明顯的問題,請原諒我。

經過大量的試驗和錯誤,我設法讓我的新Angular2組件正確降級,以便它可以在我的Angular1.4應用程序中運行。 該組件主要起作用。 唯一的問題 - 它是一個很大的問題 - 該組件忽略了我在模板級別提供的所有輸入。

我認為問題是我傳遞它們的方式。我想我可能會意外地使用Angular2方式傳遞它們而不是Angular1,但是我無法驗證它。 我所知道的是,當我從ngOnInit()中檢查我的@input()變量的值時,它們顯示為未定義,即使我通過模板傳遞硬值。

(抱歉這里的格式化,代碼似乎不會呈現為文本) Breadcrumb.html(在Angular1應用程序中):

> <breadcrumb    <!-- These two inputs are coming in as 'undefined'??--> 
>     [options]="[
>       {name: 'Option 1', disabled: false},
>       {name: 'Option 2', disabled: false},
>       {name: 'Option 3', disabled: true}
>     ]"
>     [selectedIndex]="0"
>     (selectionMade)="logOutput($event)"
>   </breadcrumb>

Breadcrumb.component.ts(在Angular2組件“breadcrumb”中):

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

@Component({
  selector: 'app-breadcrumb',
  template: require('./breadcrumb.component.html')
})
export class BreadcrumbComponent implements OnInit {
  @Input() options : Array<any>;    
  @Input() selectedIndex : number;
  @Output() selectionMade : any = new EventEmitter();

  private selected : any;

  selectOption(option: any, broadcastSelection: boolean = true) {
    if(this.selected === option || option.disabled) {
      return;
        }
    this.selected = option;
    if(broadcastSelection) {
      this.selectionMade.emit(this.selected);
        }
  }

  ngOnInit() {
        console.log('Inside breadcrumb ngOnInit!');

        console.log(options);  //<---- Showing up as undefined!
        console.log(selectedIndex); //<---- Showing up as undefined!

    if(this.selectedIndex !== undefined) {
      this.selectOption(this.options[this.selectedIndex], false);
        }
  }

}

breadcrumb.component.html:

(INSIDE BREADCRUMB DIRECTIVE) <!-- This is showing up and nothing else, because none of my @input values are coming through -->

<span class="breadcrumb" *ngFor='let option of options;let last = last'>
  <span
    (click)="selectOption(option)"
        [ngClass] = "{
            'selected' : selected,
            'disabled' : option.disabled
        }"
  >
    {{option.name}}
  </span>
  <span *ngIf="!last">
    >
  </span>
</span>

如果有人對我如何使我的Angular2組件看到我發送到它的數據有任何建議,我真的很感激它! 謝謝!

我發現了問題所在。 我忘了將輸入和輸出作為屬性包含在downgradeComponent函數參數對象中,如下所示:

index.ts的ng2Components文件夾

angular
  .module('example', [])
  .directive(
        'breadcrumb',
        downgradeComponent({
            component: BreadcrumbComponent,
            inputs: ['options', 'selectedIndex'],     //required!
            outputs: ['selectionMade']                
        }));

希望別人覺得這很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM