how to access super component class variable into sub component Class?

岁酱吖の 提交于 2019-12-06 08:57:18

You can inject a parent component into a child using angular2 Dependency Injection. Use @Inject parameter decorator and forwardRef to do it (forwardRef allows us to refer to Article which wasn't yet defined). So your AmCard component will look like (see this plunker):

@Component({
  selector: 'am-card',
  template: `
    <span>{{ articleLength }} - {{ cardTitle }}<span>
  `
})
export class AmCard {
  @Input() cardTitle: string;
  @Input() cardLink: string;
  @Input() cardAuthor: string;

  constructor(@Inject(forwardRef(() => Article)) article: Article) {
    // here you have the parent element - `article`
    // you can do whatever you want with it
    this.articleLength = article.articleArr.length;
    setTimeout(() => {
      article.articleSubmit({ value: Math.random() }, {}, {});
    }, 1000)
  }
}

But, IMHO, it's a bad pattern. If possible, it's much better to use output property (event binding) to pass message to a parent component and in a parent component handle that message. In your case it would look like (see this plunker):

@Component({ /* ... component config */})
class AmCard {
  // ... input properties
  @Output() callSubmit = new EventEmitter();

  constructor() {
    setTimeout(() => {
      // send message to a parent component (Article)
      this.callSubmit.next({ value: Math.random() });
    }, 1000)
  }
}

@Component({
  // ... component config
  template: `
    <h3>Article array:</h3>
    <div *ng-for="#item of articleArr">
      <am-card 
        [card-title]="item.title" 
        [card-link]="item.url" 
        [card-author]="item.user"
        `/* handle message from AmCard component */+`
        (call-submit)=" articleSubmit($event, {}, {}) " 
      ></am-card>
    </div>
  `
})
class Article{
  // ... properties and constructor

  articleSubmit(aa, an, au) {
    this.articleArr.push({ title: as.value, user: an.value, url: au.value });
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!