【问题标题】:How do I change the HTML/CSS of a child component from parent in Angular 2+?如何在 Angular 2+ 中从父组件更改子组件的 HTML/CSS?
【发布时间】:2020-04-14 10:08:59
【问题描述】:

我有一个组件指令,可以将一堆请求转换成一个表格。有没有办法从父逻辑有条件地将文本(HTML 和 CSS)附加到此子组件中的指定行?

(父):

<body>
   <child-component></child-component>
</body>

(孩子):

<div *ngfor = "let record in records">
   <table>
     <tr>
       <td> Class: {{ alias }} </td>
     </tr>
   </table>
</div>

澄清:如果我想通过父代码添加或编辑别名为 foo 的行的 HTML/CSS 并显示:Class: foo (in-session)

编辑:“标签”不是指代码标签(即&lt;p&gt;),我指的是附加文本。

【问题讨论】:

  • 您好 Tyree,欢迎使用 StackOverflow。你能详细说明一下你的意图是什么,到目前为止你做了什么来实现它,你到底卡在哪里?
  • 谢谢。子组件是应用程序其他部分可重用的组件。我无法直接编辑它,所以我试图从父母那里进行编辑。我尝试使用属性指令来做到这一点,但我不确定它在这种情况下如何应用。所以这让我陷入了如何准确访问这些元素的问题上。这有帮助吗?
  • 正如@SiddAjmera 所指出的,它仍然不清楚你在问什么。您需要以明确的要求更新问题,也可以在 stackblitz 上提供问题的最小复制。

标签: javascript angular components parent-child angular-directive


【解决方案1】:

您可以通过 angular 的 @Input() 装饰器结合 angular 中的 dynamic scss/css 类分配来提出解决方案。在您的子组件中,您可以像这样分配动态 css

`[ngClass]="{'CSS-CLASS': CONDITION-HERE,'CSS-CLASS':CONDITION-HERE}"`

在您的具体情况下,子 component.html:

<div *ngfor = "let record in records">
   <table>
     <tr>
       <td> [ngClass]="{'foo': record==record.name=='foo'}" {{ alias }} </td>
     </tr>
   </table>
</div>

PS:- 您可以根据需要编辑类 'foo' 的条件。

在您的子 component.ts 中:

   export class ChildComponent implements OnChanges {

      @Input() public rercord: any[];


      constructor() {
      }
   }

只要您想在父组件中使用子组件,只需使用以下内容:

<body>
   <child-component [records]="fetchedRecords"></child-component>
</body>

在父组件内.ts:

export class ParentComponent {

         public fetchedRecords: any;


          constructor(public myService:MyService) {
          this.myService.getValues().subscribe((rowData)=>{
            this.fetchedRecords = rowData;
           });
          }
       }

【讨论】:

  • 谢谢。这是最接近我正在寻找的解决方案。我意识到我要问的是不可能的。我必须以某种方式编辑子组件以接受父组件所做的更改。
  • 没问题,您介意对我提供的答案投赞成票吗?提前致谢
猜你喜欢
  • 1970-01-01
  • 2018-11-23
  • 2020-03-08
  • 2017-05-18
  • 1970-01-01
  • 2019-06-05
  • 2019-11-26
  • 2016-08-30
  • 2021-02-10
相关资源
最近更新 更多