javascript - 使用 angular5 打印屏幕无法获取其中的值
问题描述
在这里,我试图获取打印屏幕中的值,但我得到了我在屏幕截图下面附加的空值。我只想在打印屏幕中获取值,或者是它的任何模块
这是我的 component.ts 文件
printDiv() {
const divContents = document.getElementById('dvContents').innerHTML;
const printWindow = window.open('', '');
printWindow.document.write('<html><head><title>Process Compensation Report</title>');
printWindow.document.write('</head><body style="color: black">');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
}
这里是html文件
<section id="dvContents" style="color: white;" class="form_cont">
<div class="container">
<div class="row mt-20">
<div class="col-md-4 col-sm-4 text-right res-tleft">
<label>Name</label>
</div>
<div class="col-md-4 col-sm-4">
<input type="text" [(ngModel)]="name" > **// this is not printing**
</div>
<div class="col-md-4 col-sm-4" *ngIf="arcButt">
<button class="btn btn-gradient-txt" type="button" (click)="archiveButt();">
<span style="font-size: 14px">
<i class="fa fa-file-archive-o"></i> Archive</span>
</button>
</div>
</div>
解决方案
问题不是(直接)有角度的。问题是您正在阅读innerHtml
它只会为您提供innerHtml
可以提供的信息 - 那些是标签上定义的属性的值。
让我解释。假设您有以下 html(暂时忘记 angular):
<input type="text" value="42" >
这是一个输入字段,输入“文本”。在它上面我们应用了一个属性。
value="42"
现在,您假设更改输入字段的值会更改属性的值 - 也许您认为它们是相同的。这是一个常见的错误:实际上,对象(元素节点)的 (value) 属性是一回事,而 (value) 属性是另一回事。它们显然是相关的,但并不相同。
也许一个例子可以更清楚地说明这一点:
element.value = "42"
这会将元素的“值”属性设置为“42”。属性值不受影响。以下将属性的值设置为“42”
element.setAttribute("value", "42")
现在,大多数浏览器可能会检测到DOM 上value属性的变化,并相应地更改实际元素上的 value属性,但它们仍然是独立的身份。
例如,当浏览器渲染时
<input type="text" value="Bob">
,它会创建一个对应的 DOM 节点,其 value 属性初始化为“Bob”。当用户在输入框中输入“Sally”时,DOM 元素值属性变为“Sally”。但是当您向输入元素询问该属性时,HTML value 属性保持不变:
input.getAttribute('value')
返回“Bob”。
作为证明,请考虑以下示例 - 它甚至不使用角度:
function showInnerHtml() {
console.log(document.getElementById('questionField').innerHTML);
}
<div id="questionField">
<input id="questionField" type="text" value="420">
<button type="button" onClick="showInnerHtml()">Button</button>
</div>
尝试更改输入字段中的值,然后按下按钮。您将看到属性上的值不会反映您的更改 - 只有属性会。
因此,您尝试做的事情本身是不可能的。
也就是说,如果你真的必须这样做,有一种可能的(没有必要在每个浏览器上工作)的解决方法。Angular 可以使用特殊的 [attr.name] 语法来绑定到属性值。这意味着您实际上可以创建与 HTML 属性值属性的绑定。
请参阅此 stackblitz 以获取有关此的快速 POC,如果需要,请随时要求更多说明。