在角度为6/7的多个分量中使用与子状态不同的相同分量

时间:2018-12-15 09:21:42

标签: angular components angular6 angular-components angular7

enter image description here

我有一个ErrorComponent,我要在其中添加两个。 1是父母,其他是其孩子。问题是两个组件都采用相同实例的错误组件。因此,每当我只想在父组件中显示错误时,它也会在子组件上显示,反之亦然。

我想将两个errorcomponent都保留为不同的实例。请帮忙。提前致谢。

您可以在https://stackblitz.com/edit/angular-21woxg?file=src%2Findex.html

处使用代码

2 个答案:

答案 0 :(得分:0)

您可以做的是提供您希望它们动态化的内容作为输入,然后您就可以为Error组件设置不同的状态,例如,如果您要自定义错误消息,您添加的import boto3 id_token='aaaaaa.bbbbbbbb.cccccccc' #Got from the url salesforce sends after successful authentication client = boto3.client('cognito-identity', 'us-east-2') resp = client.get_id(AccountId='123456789123', IdentityPoolId='us-east-2:xxxxxxx-yyyy-zzz-hhhhh-jj888hhhh', Logins={ 'provider_url': id_token } )

error-component.ts

然后在您的export class ErrorComponent { @Input()ErrorMessage='default error' }

parent-component.html

并在您的<my-error-component [ErrorMessage]="http failure .."> </my-error-component>

child-component.html

答案 1 :(得分:0)

到目前为止,您将无法使用这种实现。原因是,ErrorComponentParentComponent的模板中都使用了ChildComponent。而且您没有任何一种逻辑可以在ErrorComponentParentComponent的模板中有条件地显示ChildComponent

话虽如此,要使这项工作有效,您必须执行以下操作:

  1. 从您的拦截器服务中发送一个字段,该字段确定需要在何处显示错误消息(示例中的showOn
  2. 使ErrorComponent成为愚蠢的组件。只要让它接受errors作为@Input
  3. 在您的ParentComponentChildComponent中注入NotifyService作为依赖项并订阅errorNotifications。由于我们正在通过拦截器服务设置showOn属性,因此这两个订阅将接收的错误对象也将具有此showOn属性。
  4. 基于此,您可以在displayErrorParentComponent上设置ChildComponent属性。然后,您还可以将其用于*ngIf,以有条件地显示ErrorComponent

这是您推荐的Working Sample StackBlitz