在子组件中覆盖父组件样式

时间:2018-10-10 12:59:11

标签: css angular

我有一个上级组件parent.html,它具有CSS样式,如下所示

.style1{
color:red
}
.style2{
color:red
}

,我正在child.html中重用此组件。现在,我想覆盖子组件中的父组件样式。 我尝试使用::ng-deep正常工作,但是如果加载Parent component,子组件中的样式替代也将反映在父组件中。.

我只想覆盖子组件中的样式,而不能覆盖父组件中的样式。我们该怎么做?

2 个答案:

答案 0 :(得分:1)

为此,您需要在父级中使用class WkAccount < ActiveRecord::Base unloadable belongs_to :address, :class_name => 'WkAddress', :dependent => :destroy has_many :billable_projects, as: :parent, class_name: "WkAccountProject", :dependent => :destroy has_many :invoices, as: :parent, class_name: "WkInvoice", :dependent => :restrict_with_error has_many :invoice_items, through: :invoices has_many :custom_values, -> { where(custom_field: CustomField.where(field_format: "company"))}, :foreign_key => "value", :primary_key => "id_s", :dependent => :destroy has_many :projects, through: :billable_projects has_many :contracts, as: :parent, class_name: "WkContract", :dependent => :destroy has_many :opportunities, as: :parent, class_name: "WkOpportunity", :dependent => :destroy has_many :activities, as: :parent, class_name: 'WkCrmActivity', :dependent => :destroy has_many :contacts, foreign_key: "account_id", class_name: "WkCrmContact", :dependent => :destroy has_many :payments, as: :parent, class_name: "WkPayment" belongs_to :location, :class_name => 'WkLocation' validates_presence_of :name validate :hasAnyValues def id_s read_attribute(:id).to_s end def hasAnyValues name.blank? && address_id.blank? && activity_id.blank? && industry.blank? && annual_revenue.blank? && assigned_user_id.blank? && id.blank? end # Returns account's contracts for the given project # or nil if the account do not have contract def contract(project) contract = nil unless project.blank? contract = contracts.where(:project_id => project.id).first contract = contracts[0] if contract.blank? end contract end end ,然后才能通过添加更具体的选择器(如子组件-

)来添加覆盖。
encapsulation: ViewEncapsulation.None

答案 1 :(得分:0)

我认为您必须具有两个具有两个单独目录的组件,并且应该具有html,ts,css文件。

因此,在父组件的html中,您将引用子组件-
parent.component.html -> <app-child> </app-child>

在子组件中,您应该具有-child.component.html,child.component.ts,child.component.css文件。
如果您在child.component.css中创建并添加任何类似的样式(例如parent.component.css文件),则这些样式将被添加到p[random_atttr_value]之类的每个组件中,因此,您现在将为child中的p提供单独的样式。

这是angular的默认行为,用于视图封装。并非所有浏览器都支持有角度的阴影DOM技术,例如有角度的阴影DOM技术。
换句话说,它为浏览器上呈现的每个组件添加了一些属性。
ViewEncapsulation具有3个选项-

encapsulation: ViewEncapsulation.None, 
           ViewEncapsulation.Emulated, (-- this is default)
           ViewEncapsulation.Native (-- only applies to browsers with shadow DOM technology)<br>

希望这将帮助您解决问题。