각도 2 - 내부HTML 스타일
저는 HTTP 통화에서 HTML 코드 덩어리를 받고 있습니다.변수에 HTML 블록을 넣고 [innerHTML]로 페이지에 삽입했는데 삽입된 HTML 블록에 스타일을 지정할 수 없습니다.제가 이것을 어떻게 달성할 수 있을지에 대해 제안하는 사람이 있나요?
@Component({
selector: 'calendar',
template: '<div [innerHTML]="calendar"></div>',
providers: [HomeService],
styles: [`h3 { color: red; }`]
})
제가 스타일링하고 싶은 HTML은 "일정관리" 변수에 포함된 블록입니다.
2 업트이 2::slotted
::slotted이제 모든 새 브라우저에서 지원되며 에서 사용할 수 있습니다.ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/ :: 업데이트됨
업데이트 1::ng-deep
/deep/더 이상 사용되지 않고 다음으로 대체되었습니다.::ng-deep.
::ng-deep또한 이미 더 이상 사용되지 않는 것으로 표시되었지만 아직 사용 가능한 대체품이 없습니다.
때ViewEncapsulation.Native DOM합니다.::ng-deep아마 중단될 것입니다.
원래의
Angular는 DOM에 추가하는 HTML에 모든 종류의 CSS 클래스를 추가하여 섀도 DOM CSS 캡슐화를 에뮬레이트하여 구성 요소로 들어오고 나가는 스타일을 방지합니다.Angular는 또한 이러한 추가된 클래스와 일치하도록 추가한 CSS를 다시 씁니다.의 HTML우를 사용하여 추가된 [innerHTML]이러한 클래스는 추가되지 않으며 다시 작성된 CSS가 일치하지 않습니다.
해결 방법으로
- 구성 요소에 추가된 CSS의 경우
/* :host /deep/ mySelector { */
:host ::ng-deep mySelector {
background-color: blue;
}
- 에 추가된
index.html
/* body /deep/ mySelector { */
body ::ng-deep mySelector {
background-color: green;
}
>>>에 상응하는 것 (및그에상는것하당것)및는)/deep/그렇지만/deep/ 및 더 잘 합니다.::shadow2.0.0-1987.10에 되었습니다.은 섀도 CSS 결합기사용되지 와하며, 오직 "DOM CSS 결합기"("DOM CSS 결합기")와만합니다.encapsulation: ViewEncapsulation.EmulatedAngular2의 기본값입니다.그들은 아마도 또한 일을 할 것입니다.ViewEncapsulation.None하지만 필요하지 않기 때문에 무시됩니다.이러한 결합기는 구성요소 간 스타일링을 위한 고급 기능이 지원되기 전까지는 중간 솔루션에 불과합니다.
또 다른 접근 방식은
@Component({
...
encapsulation: ViewEncapsulation.None,
})
CSS를 차단하는 모든 구성 요소(CSS를 추가하는 위치와 스타일을 지정하려는 HTML 위치에 따라 다름 - 응용 프로그램의 모든 구성 요소일 수 있음)
갱신하다
당신이 따라야 할 간단한 해결책은
import { DomSanitizer } from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer){}
transformYourHtml(htmlTextWithStyle) {
return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}
.[innerHTML]="content.title"를 배치합니다.styles.scss구성 요소의 scss 파일이 아닌 파일입니다.CMS는 의도적으로 인라인 스타일을 제거하므로 작성자가 콘텐츠에 사용할 수 있는 클래스를 준비해야 합니다.사용기를 사용하는 것을 하세요.{{content.title}}템플릿에서 내용에서 HTML을 렌더링하지 않습니다.
Angular 구성요소 내부에 동적으로 추가된 HTML 요소의 스타일을 지정하려는 경우 다음과 같은 작업이 유용할 수 있습니다.
// inside component class...
constructor(private hostRef: ElementRef) { }
getContentAttr(): string {
const attrs = this.hostRef.nativeElement.attributes
for (let i = 0, l = attrs.length; i < l; i++) {
if (attrs[i].name.startsWith('_nghost-c')) {
return `_ngcontent-c${attrs[i].name.substring(9)}`
}
}
}
ngAfterViewInit() {
// dynamically add HTML element
dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}
내 생각에 이 특성에 대한 규칙은 Angular 버전 간에 안정적이지 않기 때문에 Angular의 새 버전으로 업그레이드할 때 이 솔루션에 문제가 발생할 수 있습니다(그러나 이 경우 이 솔루션을 업데이트하는 것은 사소한 일이 될 수 있습니다).
하여 다음방사여용하을 CSS에서 합니다.innerhtml.
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
.
html: SafeHtml;
constructor(protected _sanitizer: DomSanitizer) {
this.html = this._sanitizer.bypassSecurityTrustHtml(`
<html>
<head></head>
<body>
<div style="display:flex; color: blue;">
<div>
<h1>Hello World..!!!!!</h1>
</div>
</div>
</body>
</html>`);
}
예제 코드 스택 블리츠
또는 아래 방법을 사용하여 HTML로 직접 작성합니다.https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1
귄터 조흐바우어의 추천 버전은 잘 작동하지만, 추가로 만들 것이 있습니다.저의 경우, 저는 스타일이 맞지 않는 html 요소를 가지고 있었고 어떻게 스타일링해야 할지 몰랐습니다.그래서 저는 파이프에 스타일링을 더하기 위해 파이프를 디자인했습니다.
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
const style = ` style = "${styleSelector}: ${styleValue};"`;
const indexPosition = html.indexOf('>');
const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
return this.sanitizer.bypassSecurityTrustHtml(newHtml);
}
}
그런 다음 다음과 같은 HTML 요소에 스타일을 추가할 수 있습니다.
<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>
포함:
Variable = '<p> Test </p>'
원하는 사람은 이너에 특정 스타일을 적용하면 됩니다.HTML:
팔로우 안전한 HTML 파이프 만들기
그리고 HTML 문자열을 다음과 같은 CSS 스타일로 연결할 수 있습니다.
return this.sanitizer.bypassSecurityTrustHtml(value+='<style type="text/css">.image img { width: 100% }</style>');
것이.value,)에서 온 것입니다(아래, ...).인수)에서 가져온 것입니다.
가장 쉽고 간단한 방법은 각 프로젝트 src 폴더에 있는 전역 스타일 파일을 사용하는 것입니다.
구성 요소 선택기가 app-my-component라고 가정합니다.
app-my-component 템플릿에서 내부 Html 콘텐츠를 호스팅하는 요소에 클래스를 추가합니다.
<div class="innerhtml-class" [innerHTML]="variable.innerHtml"></div>
전역 스타일 파일에 추가:
app-my-component {
.innerhtml-class {
declaration goes here
}
}
나는 갔습니다.this.sanitizer.bypassSecurityTrustHtml()를 " " " ", " "로 설정합니다.ViewEncapsulation.NONE하지만 두 가지 문제가 있었습니다.
ViewEncapsulation.NONE요소에 했습니다.- 내 "안전한" html은 css 변수, 즉 var(--blue)와 함께 작동하지 않는 것 같습니다.
이것은 저에게 효과가 있었습니다(다른 것을 변경할 필요 없이). 인접 삽입HTML
템플릿:
<div id=template></div>
코드:
ngOnInit() {
const el = document.getElementById('template');
el.insertAdjacentHTML('afterbegin', `<span style="color: var(--blue)">hello</span>`);
}
고지 사항:저의 경우, 저는 구성 파일에서 html을 구문 분석하고 있었습니다.당신은 사용자가 입력한 html로 이 경로를 가고 싶지 않을 것입니다.
동적인 스타일이 제한된 경우 인라인 CSS 변수를 사용하는 것이 대안 솔루션입니다.
예.
// file.ts
someVarWithHtml = 'Hello <span class="dynamic">World</span>';
// file.ng.html
<div [style]="'--my-var: ' + value"
[innerHTML]="someVarWithHtml"></div>
// style.css
.dynamic {
background: var(--my-var);
}
내부에서 CSS 클래스를 사용할 수 있는 대안 [inner]HTML]은 styles.scss와 같은 글로벌 파일로 선언하는 것입니다.이 파일은 angular.json에 지정되어 있습니다.
"styles": [
"./node_modules/flexboxgrid/dist/flexboxgrid.min.css",
"src/styles.scss"
],
스타일 전처리기로 sas를 사용하는 경우 다음을 통해 개발 종속성을 위해 네이티브 sas 컴파일러로 다시 전환할 수 있습니다.
npm install node-sass --save-dev
개발을 위해 /deep/를 계속 사용할 수 있도록 합니다.
언급URL : https://stackoverflow.com/questions/36265026/angular-2-innerhtml-styling
'programing' 카테고리의 다른 글
| SQL Server의 테이블에서 Xml 값 및 속성을 쿼리하는 방법은 무엇입니까? (0) | 2023.05.29 |
|---|---|
| Node.js와 함께 사용할 웹 소켓 라이브러리는 무엇입니까? (0) | 2023.05.29 |
| RabbitMQ / AMQP: 동일한 메시지에 대해 단일 대기열, 다중 소비자? (0) | 2023.05.29 |
| 현재 사용 중인 대화형 셸을 확인하는 방법(명령줄) (0) | 2023.05.29 |
| iOS 10에서 Xcode 7 사용 (0) | 2023.05.29 |